现在的位置: 首页 > 综合 > 正文

leetcode Reorder List(*)

2018年10月27日 ⁄ 综合 ⁄ 共 846字 ⁄ 字号 评论关闭

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

利用快慢指针把链表一分为二,再把后半部分链表求倒序,然后合并前后半部分链表。(一定注意边界条件,没有元素,只有一个元素等情况!)

/**
 * 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==NULL)return;
        ListNode *cur=head,*mid=head,*midnext,*midnextnext;
        while(cur){
            cur=cur->next;
            if(cur)cur=cur->next;
            else break;
            if(cur)mid=mid->next;
        }
        midnext=mid->next;
        while(midnext&&midnext->next){
            midnextnext=midnext->next;
            midnext->next=midnextnext->next;
            midnextnext->next=mid->next;
            mid->next=midnextnext;
        }
        cur=head;
        while(cur!=mid){
            midnext=mid->next;
            mid->next=midnext->next;
            midnext->next=cur->next;
            cur->next=midnext;
            cur=midnext->next;
        }
    }
};

抱歉!评论已关闭.