Question about Using Deque


  • 0
    J

    Hey Guys

    I want to solve this problem by using a deque. I put every single ListNode* of the linked list in the deque with their default order. Then I pick ListNode* from both side of the deque and reorder the Linked List. My method failed the last test case but when I debug it in the playground I got correct output in the debug mode. Here I attached my code below and I wonder can anyone help me figure out where my problem is??

    '''
    /**

    • 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) {
      deque<ListNode*> mydeq;
      ListNode* cur = head;
      while(cur != NULL)
      {
      mydeq.push_back(cur);
      cur = cur->next;
      }
      ListNode* f;
      ListNode* b;
      ListNode* last;
      while(!mydeq.empty())
      {

           f = mydeq.front();
           mydeq.pop_front();
           if(b != NULL)
               b->next = f;
           last = f;
           if(!mydeq.empty())
           {
               b = mydeq.back();
               mydeq.pop_back();
               f->next = b;
               last = b;
           }
       }
       if(last != NULL)
           last->next = NULL;
      

      }
      };
      '''


Log in to reply
 

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