leetcode-Reorder List

Difficulty: Medium

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) {
        if(!head)
            return ;
        deque<ListNode*> que;
        ListNode *p=head;
        while(p){
            que.push_back(p);
            p=p->next;
        }
        head=new ListNode(-1);
        p=head;
        while(!que.empty()){
            ListNode *t1=que.front();
            ListNode *t2=nullptr;
            que.pop_front();
            if(!que.empty()){
                t2=que.back();
                que.pop_back();
            }
            p->next=t1;
            p=p->next;
            p->next=t2;
            p=p->next;
       }
       if(p)
            p->next=nullptr;
        p=head;    
        head=head->next;
        free(p);
    }
};


你可能感兴趣的:(leetcode-Reorder List)