Leetcode143重排链表 (大白话说思路)——链表专题

思路:
非官方做法,我的第一直觉代码如下,用hash表记录pre节点,双指针不断将末尾节点移到前面,更新指针向中心移动,直到p!=q&&p->next!=q
时间复杂度和空间复杂度都很高,但是能过

class Solution {
public:
    void reorderList(ListNode* head) {
        ListNode*p = head;
        ListNode*q = head;
        //记录pre hash表查询前一个节点
        unordered_maphash;
        while(q->next!=NULL){
            hash[q->next] = q;
            q = q->next;
        }
        while(p!=q&&p->next!=q){
            //双指针 
            ListNode* nextp = p->next;
            ListNode* nextq = hash[q];
            hash[q]->next = NULL;
            q->next = nextp;
            p->next = q;
            p = nextp;
            q = nextq;
        }
    }
};

官方做法,三步走:
1.快慢指针找中点
2.翻转后半段
3.交叉合并前半段和翻转后的后半段

class Solution {
public:
    void reorderList(ListNode* head) {
        //快慢指针找中点
        auto slow = head,fast =head;
        while(fast->next!=NULL&&fast->next->next!=NULL){
            slow = slow ->next;
            fast = fast->next;
            fast = fast->next;
        }
        auto q = slow->next;
        slow->next = NULL;
        
        //反转newhead的链表
        ListNode* p = NULL;
        while(q!=NULL){
            auto nextq = q->next;
            q->next = p;
            p = q;
            q = nextq;
        }
    
        ListNode* k = head;
        //合并 p head两个链表
        while(p!=NULL){
            ListNode *nexthead = head->next;
            ListNode* nextp = p->next;
            head->next = p;
            p->next = nexthead;
            head = nexthead;
            p = nextp;
        }

        head = k;

    }
};

你可能感兴趣的:(leetcode,数据结构,c++)