Leetcode 143. Reorder List

原题:

Given a singly linked list L: L0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-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}.



解题方法:

考到了链表的好几个知识点:

- 用快慢指针找到链表的中点。

- 将后半部分的链表倒序。

- 将两部分的链表交叉合并到一起。


代码:
void reorderList(ListNode* head) {
        if (!head || !head->next)
            return;
        
        ListNode* cur = head, *fast = head;
        while(fast && fast->next){
            cur = cur->next;
            fast = fast->next->next;
        }
        
        ListNode* part2 = cur->next;
        cur->next = NULL;
        
        ListNode* prev = NULL;
        while(part2){
            ListNode* next = part2 ->next;
            part2->next = prev;
            prev = part2;
            part2 = next;                
        }
        
        part2 = prev;
        
        ListNode* part1 = head;
        while(part2){
            ListNode* next1 = part1 ->next;
            ListNode* next2 = part2 ->next;
            part1->next = part2;
            part2->next = next1;
            part1 = next1;
            part2 = next2;
        }        
    }




你可能感兴趣的:(Leetcode,C++)