一道鏈表相關的筆試題

從網上搜到的筆經:

題目大致如下:

寫代碼。把一個單鏈表,按照指定位置逆序。並在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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章