天天看點

劍指offer——反轉連結清單

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        if(pHead==nullptr||pHead->next==nullptr)//空或者隻有一個節點
            return pHead;
        ListNode *pre,*mid,*post;
        pre=pHead;
        mid=pre->next;
        while(mid){
            post=mid->next;
            mid->next=pre;
            if(pre==pHead)//需要把第一個節點的next設定為nullptr
                pre->next=nullptr;
            pre=mid;
            mid=post;
        }
        return pre;
    }
};      

繼續閱讀