[LeetCode] Reorder List

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;

        }
};

 

posted @ 2015-06-24 15:16  穆穆兔兔  阅读(211)  评论(0编辑  收藏  举报