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

[LeetCode] Reorder List

时间:2015-06-24 16:18:59      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:

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

 

Hide Tags
 Linked List
 

分析:用stack保存link List,然后从后向前弹出,

cur < total/2 时完成,最后把最后一个节点的next设置成NULL

 

/**
 * 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* pFront = head;
            stack<ListNode*> st; 
            int totalNum = 0;
            int curNum = 0;

            while(pFront)
            {   
                st.push(pFront);
                pFront= pFront->next;
                totalNum++;
            }   

            pFront = head;
            ListNode* pRear =  NULL;

            ListNode* tmp = NULL;
            while(curNum < totalNum/2)
            {   
                pRear = st.top();
                st.pop();

                tmp = pFront->next;
                pFront->next = pRear;
                pRear->next = tmp;
                pFront= tmp;
                curNum ++; 
            }   

            //mark the end
            pFront->next = NULL;

        }
};

 

[LeetCode] Reorder List

标签:

原文地址:http://www.cnblogs.com/diegodu/p/4597791.html

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