143. Reorder List

问题描述:

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

You may not modify the values in the list's nodes, only nodes itself may be changed.

Example 1:

Given 1->2->3->4, reorder it to 1->4->2->3.

Example 2:

Given 1->2->3->4->5, reorder it to 1->5->2->4->3.

 

解题思路:

分三步:

  1.找到中点并且将链表断成两个链表

  2.将第二个链表翻转

  3.将第一个链表和第二个链表穿插起来

需要注意的是:

  当链表节点为奇数个时,此时l2(也就是后半部分链表)会剩余一个,可能会被丢掉

  所以添加高亮处来防止被丢掉

 

代码:

/**
 * 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 || !head->next->next)
            return;
        //find the middle point
        ListNode* fast = head;
        ListNode* slow = head;
        ListNode* pre = head;
        while(fast && fast->next){
            pre = slow;
            slow = slow->next;
            fast = fast->next->next;
        }
        pre->next = NULL;
        //reverse the second part
        pre = slow;
        slow = slow->next;
        pre->next = NULL;
        while(slow){
            ListNode* temp = slow->next;
            slow->next = pre;
            pre = slow;
            slow =temp;
        }
        ListNode *l1 = head, *l2 = pre;
        while(l1 && l2){
            ListNode* temp1 = l1->next;
            ListNode* temp2 = l2->next;
            l1->next = l2;
            if(temp1)
                l2->next = temp1;
            l1 = temp1;
            l2 = temp2;
        }
        
    }
};

 

posted @ 2018-06-12 13:13  妖域大都督  阅读(101)  评论(0编辑  收藏  举报