天天看點

劍指offer刷題之c++實作的反轉連結清單

#include "myHead.h"
#include "allListNode.h"
/*
反轉連結清單 。不采用頭插法。采用尾插法直接将指針掉頭 
*/
ListNode* ReverseList(ListNode* pHead) {
	if(pHead == NULL){
		return NULL;
	} 
	ListNode *pre;
	ListNode *p;
	pre = NULL;
	
	while(pHead != NULL){
		p = (ListNode *)malloc(sizeof(ListNode));
		p->val = pHead->val;
		//注釋掉的是不需要考慮的。因為即使是第一個節點,pre在外部設定的也符合 
//		if(pre == NULL){
//			pre = p;
//			cout<<"pre"<<pre->val;
//		}
//		else {
			p->next = pre;
			pre = p;
//		}		
		pHead = pHead->next;
	} 
	return pre;
}


int main(){
	ListNode *h ;
	h= createListNode();
	cout<<"before: ";
	printListNode(h);
	cout<<endl<<"after:  ";
	printListNode(ReverseList(h));
	return 1; 
} 
           

繼續閱讀