【剑指Offer-代码的鲁棒性】面试题24:反转链表

题目描述

输入一个链表,反转链表后,输出新链表的表头。

思路

一个比较经典的题目。要维护3个指针:当前结点的指针curNode、当前结点的前一个结点的指针preNode和当前结点的下一个结点的指针nextNode。首先使用nextNode保存curNode的下一个结点地址,不然链表会断掉,然后将curNode指向preNode,将preNode改为curNode,curNode改为nextNode。当当前结点curNode的下一个结点为nullptr时说明已经到达最后一个节点,curNode就是反转后的链表头。

代码如下:

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        if(pHead==nullptr)
            return nullptr;
        
        ListNode* curNode = pHead;
        ListNode* preNode = nullptr;
        ListNode* nextNode = nullptr;
        while(curNode!=nullptr){
            nextNode = curNode->next;
            curNode->next = preNode;    //注意这一行和下一行的顺序
            if(nextNode==nullptr)
                return curNode;
            preNode = curNode;
            curNode = nextNode;
        }
        return nullptr;
    }
};

猜你喜欢

转载自www.cnblogs.com/flix/p/12450857.html