Leetcode ☞ 143. Reorder List

143. Reorder List

My Submissions
Question
Total Accepted: 60546  Total Submissions: 270201  Difficulty: Medium

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}.












我的AC:(16ms,最快一批)

struct ListNode* reverseList(struct ListNode* head){
    if(!head || !head->next) return head;
    struct ListNode *p, *p1, *p2;
    p2 = head;
    p1 = NULL;
    while(p2){
        p = p2->next;
        p2->next = p1;
        p1 = p2;
        p2 = p;
    }
    return p1;
}

void reorderList(struct ListNode* head) {
    if(!head || !head->next) return;
    struct ListNode *fast, *slow, *secondPartHead;
    fast = slow = head;
    
    while(fast->next && fast->next->next){
        fast = fast->next->next;
        slow = slow->next;
    }
    secondPartHead = slow->next;
    slow->next = NULL;
    secondPartHead = reverseList(secondPartHead);
    
    struct ListNode *firstcurr = head;
    struct ListNode *secondcurr = secondPartHead;
    struct ListNode *p1, *p2;
    while(firstcurr && secondcurr){
        p1 = firstcurr->next;
        p2 = secondcurr->next;
        firstcurr->next = secondcurr;
        secondcurr->next = p1;
        firstcurr = p1;
        secondcurr = p2;
    }
}

思路:

快慢指针找中位数-->剪掉后半部-->反转后半部-->合并


注意:

1、reorderList函数类型是void。

2、最后的循环条件while(firstcurr && secondcurr【一开始落了】)。

例子:

【1,2,3,4,5,6】-->【1,2,3】和【6,5,4】-->【1,6,2,5,3,null】,【4,null】。最后一步:把4插到了3跟null中间,firstcurr 和secondcurr都是NULL。

【1,2,3,4,5,6,7】-->【1,2,3,4】和【7,6,5】-->【1,7,2,6,3,4,null】,【5,null】。最后一步:把5插到了3跟4中间,secondcurr为NULL,而firstcurr不是NULL!

所以循环条件写成while(secondcurr)即可。

你可能感兴趣的:(Leetcode ☞ 143. Reorder List)