1. 程式人生 > >leetcode+ 連結串列翻轉,注意事項都註釋了

leetcode+ 連結串列翻轉,注意事項都註釋了

點選開啟連結
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(!head) return NULL;
        if(head->next==NULL) return head;
        ListNode *pre= head;
        ListNode *cur= pre->next;
        ListNode *Next;
        int flag = 0;
        while (cur) {
            Next = cur->next;
            if(flag==0){
                pre->next = NULL; //設定第一個節點後置為NULL; 免得迴圈連結串列
                flag = 1;
            }
            cur->next = pre; //重新設定連線
            pre = cur; //移動節點
            cur = Next;
        }
        return pre;
    }
};
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(!head) return NULL;
        if(head->next==NULL) return head;
        ListNode *pre= NULL;
        ListNode *cur= head;
        ListNode *Next= NULL;
        while (cur) {
            Next = cur->next;
            cur->next = pre; //重新設定連線
            pre = cur; //移動節點
            cur = Next;
        }
        return pre;
    }
};