LeetCode:Reorder List

Reorder List

Total Accepted: 62839  Total Submissions: 277183  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}.

Subscribe to see which companies asked this question

Hide Tags
  Linked List
















思路:

1.找到链表中点(用快、慢指针);

  如:1->2->3->4->5->null,中点为3,

  如:1->2->3->4-->null,中点为2。

2.以中点为准分成两个链表:

 如:1->2->3->4->5->null,变成

         1->2->3->null,null<-4<-5;

3.将两个链表交替插入合并。


code:

/**
 * 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) {
        ListNode *slow = head;
        ListNode *fast = head;
        if(!slow || !slow->next) return; // 空链或只有一个结点,直到返回
        // 快、慢指针找到中点
        while(fast && fast->next && fast->next->next){
            fast = fast->next->next;
            slow = slow->next;
        }
        
        // 分成两段
        ListNode *p = slow->next;
        ListNode *q = p->next;
        slow->next = NULL;
        p->next = NULL;
        // 将后半段逆置
        while(q){
            ListNode *t = q->next;
            q->next = p;
            p = q;
            q = t;
        }
        // 交替合并
        q = p;
        p = head;
        while(q){
            ListNode *tp = p->next;
            ListNode *tq = q->next;
            p->next = q;
            q->next = tp;
            p = tp;
            q = tq;
        }
    }
};


你可能感兴趣的:(LeetCode,list,reorder)