Leetcode 143 Reorder List

2018-01-12 14:50:10 浏览数 (2)

Given a singly linked list L: L0→L1→…→Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…

You must do this in-place without altering the nodes' values.

For example, Given {1,2,3,4}, reorder it to {1,4,2,3}.

将链表对半分割,后半部分逆置后与前半部分交叉合并,模拟,没什么好说的。

注意小细节,不然会像我一样疯狂RE

代码语言:javascript复制
/**
 * 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 || !head->next) return;
        ListNode* p1 = head;
        ListNode* p2 = head->next;
        while (p2 && p2->next)
        {
            p1 = p1->next;
            p2 = p2->next->next;
        }
        ListNode* head2 = p1->next;
        p1->next = NULL;
        p2 = head2->next;
        head2->next = NULL;
        while (p2) 
        {
            p1 = p2->next;
            p2->next = head2;
            head2 = p2;
            p2 = p1;
        }
        p1 = head;
        p2 = head2;
        while(p2)
        {
            ListNode* t1 = p1;
            ListNode* t2 = p2;
            p1 = p1->next;
            t1->next = p2;
            p2 = p2->next;
            t2->next = p1;
        }
    }
};

0 人点赞