天天看点

剑指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; 
} 
           

继续阅读