C++ implementation using deque (double-ended queue), 64 ms


  • 0
    A
    class Solution
    {
    public:
        void reorderList(ListNode* head)
        {
            deque<ListNode*> q;
            ListNode *ptr=head;
            while(ptr!=NULL)
            {
                q.push_back(ptr);
                ptr=ptr->next;
            }
            ListNode *prev=NULL,*temp;
            int flag=0;
            while(!q.empty())
            {
                if(!flag)
                {
                    temp=q.front();
                    q.pop_front();
                }
                else
                {
                    temp=q.back();
                    q.pop_back();
                }
                if(prev)
                {
                    prev->next=temp;
                }
                prev=temp;
                flag=1-flag;
            }
            if(prev) prev->next=NULL;
            return;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.