leetcode No143. Reorder List

Question:

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

Algorithm:

用栈,这样栈的出栈顺序就是倒序,而遍历链表是正序

Accepted 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) {
        if(head==NULL || head->next==NULL)
            return;
        ListNode* pNode1=head;    //L0 L1 L2 ...
        stack<ListNode*> s;
        int count=0;
        while(pNode1){
            s.push(pNode1);
            pNode1=pNode1->next;
            count++;
        }
        pNode1=head;
        ListNode* pNode=head;
        count--;
        pNode1=pNode->next;
        while(count){
            pNode->next=s.top();
            s.pop();
            pNode=pNode->next;
            count--;
            if(count==0)
                break;
            pNode->next=pNode1;
            pNode=pNode->next;
            pNode1=pNode->next;
            count--;
        }
        pNode->next=NULL;
    }
};


你可能感兴趣的:(LeetCode)