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

[LeetCode] Reorder List

时间:2014-07-14 19:33:04      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   数据   for   

Given a singly linked list L: L0L1→…→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) {
        ListNode *p1=head,*p2=head,*pre;
        while(p2!=NULL && p2->next!=NULL)//找到后一半的开头节点head2;
        {
          pre = p1;
          p1 = p1->next;
          p2 = p2->next;
          p2 = p2->next;
        }
        
        if(p1 == p2)
            return;
        pre->next = NULL;//前一半的结尾标记
        ListNode *head2 = p1;
        
       stack<ListNode*> st;
       while(head2)
       {
         st.push(head2);
         head2 = head2->next;
       }
       p1 = head;
       ListNode *ph1,*ph2;
       while(p1 && !st.empty() )
       {
         ph1 = p1->next;
         ph2 = st.top();
         st.pop();
         p1->next = ph2;
         ph2->next = ph1;
         p1 = ph1;
       
       }
       if(!st.empty())
       {
         ph1 = st.top();
         ph1->next = NULL;
         st.pop();
         ph2->next = ph1;
       
       }

    }
};

(1)注意数据结构用stack比较方便,如果用遍历的方法,则会超时Time Limited Exceeded!
 (2)测试用例中,head包括NULL,1个结点、2个结点、3个结点、4个结点,把这几个测试正确,其余的应该就没有问题了。

 

 

[LeetCode] Reorder List,布布扣,bubuko.com

[LeetCode] Reorder List

标签:des   style   blog   color   数据   for   

原文地址:http://www.cnblogs.com/Xylophone/p/3842849.html

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