Leetcode 143. 重排链表

/**
 * 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*> q[2];
        while(head)
            q[0].push_back(head),head=head->next;
        while(q[0].size()-q[1].size()>1)
            q[1].push_back(q[0].back()),q[0].pop_back();
        ListNode* p=q[0].front(); q[0].pop_front();
        int f=1;
        while(!q[f].empty())
           p->next=q[f].front(),q[f].pop_front(),f^=1,p=p->next;
         p->next=NULL;
    }
};

猜你喜欢

转载自blog.csdn.net/Bendaai/article/details/81007566