《剑指offer》-反转链表

题目描述

输入一个链表,反转链表后,输出链表的所有元素。

《剑指offer》-反转链表_第1张图片

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        ListNode* pre = NULL;
        ListNode* pCurr = pHead;
        ListNode* pNext = NULL;
        while(pCurr != NULL){
            pNext = pCurr->next;
            pCurr->next = pre;
            pre = pCurr;
            pCurr = pNext;      
        }
        return pre;
    }
};

之前错误的写法,一直不明白

原因是移位的时候,pCurr移到下一位时,里面的值已经变成反向指针了,所以不能成功移动,就循环嵌套进去了,所以还需要一个变量pNext来存储移位前的值。

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        ListNode* pre = pHead;
        ListNode* pCurr;
        ListNode* end;
          
        while(end != NULL){
            
            pCurr->next = pre;
            pre = pre->next;
            pCurr = pre->next;
            end = pCurr->next;
        }
        pHead->next = NULL;
        end = pCurr;
        pHead = pCurr;
        return pHead;
    }
};、


你可能感兴趣的:(《剑指offer》-反转链表)