码迷,mamicode.com
首页 > 其他好文 > 详细

Reorder List

时间:2014-12-03 13:49:04      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   io   ar   color   sp   for   on   

Given a singly linked list LL0→L1→…→Ln-1→Ln,
reorder it to: L0→LnL1→Ln-1→L2→Ln-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) {
        ListNode *first = head, *middle = head, *tail = head, *pre_tail;

     if (head == NULL || head->next == NULL) { return;}

     pre_tail = middle;
     // find the middle node
     while (tail != NULL && tail->next != NULL) {
         pre_tail = middle;
         middle = middle->next;
         if (tail->next->next != NULL) {
             tail = tail->next->next;
         } else {
             tail = tail->next;
         }
     }

     ListNode *prev = NULL, *current = middle, *next=middle->next;
     while (current != NULL) {
         current->next = prev;
         prev = current;

         current = next;
         if (next != NULL) {
             next = next->next;
         }
     }

     ListNode *subHead = prev, *subNext = prev;

     current = head;
     while (current != NULL) {
         next = current->next;

         current->next = subHead;
         current = next;

         if (subHead != NULL) {
             subNext = subHead->next;
             subHead->next = next;

             subHead = subNext;
         }
     }
    }
};

 

Reorder List

标签:des   style   blog   io   ar   color   sp   for   on   

原文地址:http://www.cnblogs.com/code-swan/p/4139645.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!