链表反转

思路:
使用三个指针:p,pre,next,p指向当前需要更改的节点,pre指向这个节点的前一个节点,next指向这个节点的后一个节点。重点是更改指针的顺序,更新链首指针。

/*
只需要完成逆置链表函数
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};
*/

class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
		if(pHead==NULL||pHead->next==NULL)
            return pHead;
        ListNode* pre=pHead;
        ListNode* p=pre->next;
        ListNode* next=pre->next->next;

        while(pre->next!=NULL){
            pre->next=p->next;
            p->next=pHead;
            pHead=p;
            p=next;
            next=next->next;          
            
        
        }
        return pHead;
        
    }
};
posted @ 2015-08-31 17:10  机器狗mo  阅读(133)  评论(0编辑  收藏  举报