1. 程式人生 > >LeetCode | Reorder List(連結串列重新排序)

LeetCode | Reorder List(連結串列重新排序)

Given a singly linked list LL0L1→…→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}.

題目解析:

題目非常簡單,先將連結串列分成兩半,將後半段翻轉,然後將兩個連結串列合併就行了。

但是實現的時候各種錯誤。連結串列的問題,就是比較繁瑣,各種細節。一定要動手畫清楚才行。

class Solution {
public:
    void reorderList(ListNode *head) {
        if(head == NULL)
            return ;
        int n = 1;
        ListNode *p = head;
        while(p->next){
            n++;
            p = p->next;
        }
        if(n==1 || n==2)
            return ;

        int i = 1;
        p = head;
        while(i < n/2){
            i++;
            p = p->next;
        }
        ListNode *q = p->next;
        p->next = NULL;
        p = ReverseList(q);
        MergeList(head,p);
    }
    ListNode *ReverseList(ListNode *head){
        ListNode *p = head;
        ListNode *q = p->next;
        p->next = NULL;
        while(q){
            ListNode *h = q->next;
            q->next = p;
            p = q;
            q = h;
        }
        head = p;
        return head;
    }
    ListNode *MergeList(ListNode *head,ListNode *q){
        ListNode *p = head;
        while(p->next){
            ListNode *h = p->next;
            p->next = q;
            p = h;
            h = q->next;
            q->next = p;
            q = h;
        }
        p->next = q;
        return head;
    }
};


關於連結串列的翻轉,上面用的是非遞迴方法。也可以用遞迴方式,程式碼也確實有點意思,值得參考。

public ListNode recursive_reverse(ListNode head) {
    if(head == null || head.next==null)
        return head;
    return recursive_reverse(head, head.next);
}
private ListNode recursive_reverse(ListNode current, ListNode next) 
{
    if (next == null) return current;
    ListNode newHead = recursive_reverse(current.next, next.next);
    next.next = current;
    current.next = null;
    return newHead;
}