Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Sunday, October 15, 2017

Reverse First K elements of Queue


Idea is to use stack for first k elements.
enque all items to queue 
Deque remaining items and enque them


Code:

public Queue<Integer> modifyQueue(Queue<Integer> q, int k)
    {
      Stack<Integer> stk=new Stack<Integer>();
      int temp=k;
      int size=q.size();
      while(--temp>=0)
      {
          stk.push(q.remove());
          
      }
      while(!stk.isEmpty())
      {
          q.add(stk.pop());
      }
      temp=size-k;
      while(temp-->0)
      {
          q.add(q.remove());
      }
      return q;
    }

0 Comments:

Post a Comment

Stats