一道链表相关的笔试题

从网上搜到的笔经:

题目大致如下:

写代码。把一个单链表,按照指定位置逆序。并在code中体现基本错误异常处理之类。 

 不能再多malloc内存了,可以用temp pointers。还有一个不允许的什么条件没看懂,无 碍大雅吧。 

eg。n1->n2->n3->n4->n5->null phead = n1;pstart = n3;返回这个n3->n2->n1->n5-> n4->null 
eg。n1->n2->n3->n4->n5->null phead = n1;pstart = n5;返回这个n5->n4->n3->n2-> n1->null 
eg。n1->n2->n3->n4->n5->null phead = n1;pstart = n1;返回这个n1->n5->n4->n3-> n2->null


实现代码如下:

#include <iostream>
using namespace std;

typedef struct _node {
	int key;
	_node * next;
	_node(int k) {key = k;}
	~_node();
} node;

void reverse(node* &phead, node* &pstart) {\
	if (phead == NULL )
		return;
	if (pstart == NULL)
		return;
	node *p = phead;
	node *pnext = p->next;
	node *prev = NULL;
	while (prev!=pstart && pnext!=NULL) {
		pnext = p->next;
		p->next = prev;
		prev = p;
		p = pnext;
	}

	prev = NULL;
	
	while(pnext!=NULL) {
		pnext = p->next;
		p->next = prev;
		prev = p;
		p = pnext;
	}
	
	phead->next = prev;
	phead = pstart;

}

void main() {
	node *p = new node(1);
	node *phead = p;
	for (int i = 2; i < 6; i++) {
		p->next = new node(i);
		p = p->next;
	}
	p->next = NULL;

	node *pstart = phead;

	reverse(phead, pstart);
	
	p = phead;
	while (p!=NULL) {
		cout << p->key << " ";
		p = p->next;
	}

	cout << endl;
}


你可能感兴趣的:(一道链表相关的笔试题)