给定单链表L:L0→L1→...→Ln-1→Ln, 重新排序:L0→Ln→L1→Ln-1→L2→Ln-2→...

217 篇文章 0 订阅
174 篇文章 2 订阅

本题源自leetcode  143

----------------------------------------------------------------------------

思路1:用快慢指针找到中节点,然后反转后半部分链表。然后俩个链表交叉插入

代码:

void reorderList(ListNode* head) {
        if (!head || !head->next) 
            return;
    
        // find the middle node: O(n)
        ListNode *slow = head, *fast = head;
        while (fast && fast->next && fast->next->next) {
            slow = slow->next;
            fast = fast->next->next;
        }

        // cut from the middle and reverse the second half: O(n)
        ListNode *head2 = slow->next;
        slow->next = NULL;

        ListNode *q = head2->next;
        head2->next = NULL;
        while (q) {
            ListNode *qNext = q->next;
            q->next = head2;
            head2 = q;
            q = qNext;
        }
        ListNode* p = head;
        // merge two lists: O(n)
        for (q = head2; p; ) {
            auto t = p->next;
            p->next = q;
            p = p->next;
            q = t;
        }
        /*
        slow->next = reverse(slow->next);
        ListNode* q = slow->next; 
        //reverse(slow->next);
        while(p != slow && q ){
            ListNode * qNext = q->next;
            q->next = p->next;
            p->next = q;
            p = q->next;
            q = qNext;
        }
        */
    }

代码2:

 void reorderList(ListNode* head) {
        if (!head || !head->next) 
            return;
    
        // find the middle node: O(n)
        ListNode *slow = head, *fast = head;
        while (fast && fast->next && fast->next->next) {
            slow = slow->next;
            fast = fast->next->next;
        }

        // cut from the middle and reverse the second half: O(n)
        ListNode *head2 = reverse(slow->next);
        slow->next = NULL;
        ListNode* p = head, *q = head2;
        /*
        // merge two lists: O(n)
        for (; p; ) {
            auto t = p->next;
            p->next = q;
            p = p->next;
            q = t;
        }
        */
        //reverse(slow->next);
        while(p  && q ){
            ListNode * qNext = q->next;
            q->next = p->next;
            p->next = q;
            p = q->next;
            q = qNext;
        }
    }
    
    ListNode* reverse(ListNode* root){
        if(!root)
            return NULL;
        ListNode* pre = NULL;
        ListNode* p = root;
        ListNode* pNext = NULL;
        while(p){
            pNext = p->next;
            p->next = pre;
            pre = p;
            p = pNext;
        }
        return pre;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值