美文网首页Leetcode
Leetcode 143. Reorder List

Leetcode 143. Reorder List

作者: SnailTyan | 来源:发表于2018-10-14 15:50 被阅读5次

    文章作者:Tyan
    博客:noahsnail.com  |  CSDN  |  简书

    1. Description

    Reorder List

    2. Solution

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        void reorderList(ListNode* head) {
            if(!head) {
                return;
            }
            ListNode* p1 = head;
            ListNode* p2 = head;
            while(p2 && p2->next) {
                p1 = p1->next;
                p2 = p2->next->next;
            }
            ListNode* left = head;
            ListNode* right = reverseList(p1->next);
            p1->next = nullptr;
            ListNode* new_head = new ListNode(0);
            ListNode* current = new_head;
            while(left && right) {
                current->next = left;
                left = left->next;
                current = current->next;
                current->next = right;
                current = current->next;
                right = right->next;
            }
            current->next = left?left:right;
            head = new_head->next;
        }
        
    private:
        ListNode* reverseList(ListNode* head) {
            ListNode* pre = nullptr;
            ListNode* next = nullptr;
            ListNode* current = head;
            while(current) {
                next = current->next;
                current->next = pre;
                pre = current;
                current = next;
            }
            return pre;
        }
    };
    

    Reference

    1. https://leetcode.com/problems/reorder-list/description/

    相关文章

      网友评论

        本文标题:Leetcode 143. Reorder List

        本文链接:https://www.haomeiwen.com/subject/miazaftx.html