當前位置:網站首頁>143. 重排鏈錶

143. 重排鏈錶

2022-01-28 08:59:18 無問東西 聽從我心

尋找鏈錶中點 + 鏈錶逆序 + 合並鏈錶

/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */
class Solution {
    
public:
    void reorderList(ListNode* head) {
    
        ListNode* midnode = head;
        ListNode* fast  =head;
        while(fast != nullptr && fast->next != nullptr){
    
            midnode = midnode->next;
            fast = fast->next->next;
        }
        ListNode* left = head;
        ListNode* right = midnode->next;
        midnode->next  = nullptr;

        ListNode*pre = nullptr;
        ListNode*cur = right;
        while(cur != nullptr){
    
            ListNode* node = cur->next;
            cur->next = pre;
            pre = cur;
            cur = node;
        }
        right = pre;

        //ListNode* res = left;
        while(left->next != nullptr && right!=nullptr){
    
            ListNode* nextnode = left->next;
            left->next = right;
            right= right->next;
            left->next->next = nextnode;
            left=left->next->next;
        }
       // return res;
    }
};

版權聲明
本文為[無問東西 聽從我心]所創,轉載請帶上原文鏈接,感謝
https://cht.chowdera.com/2022/01/202201280859178279.html

隨機推薦