1 1 vote I have a doubt regarding " implementing queue using 2 stacks " For an EQueue operation there is a push operation in one of the stack that is OK but when we are doing first DQueue operation why we need to pop each element from from one stack and push all into other stack rather than pop elements from one stack until it has one element and after that pop that element from the same stack . Data Structures + – saurabh rai 1.2k views answer comment Share Follow Print 0 reply Please log in or register to add a comment.
1 1 vote Because if you won't push them onto 2nd stack you will lose elements after first one. So when you perform dequeue next time from where will second element come so that we can dequeue it Shivam Chauhan answered Oct 5, 2016 Shivam Chauhan comment Share Follow See all 7 Comments 7 7 Comments reply saurabh rai commented Oct 5, 2016 reply Follow flag for second DQueue pop from 2nd stack . 0 0 replyShare mcjoshi commented Oct 5, 2016 reply Follow flag For implementing queue using stack our main aim is to exhibit (FIFO) property. So, we are supposed to perform PUSH and POP on $2$ stacks in an order that maintains this property (FIFO) . Suppose you are required to form a queue containing $10$ elements. Push all elements in first stack. (now if you pop all elements, order will be reversed) Stack-1 : $10,9,8,7,6,5,4,3,2,1$ Pop all elements from first stack, and place them in second stack. ($10$ will now go to bottom of second stack) Stack-2: $1,2,3,4,5,6,7,8,9,10$ Now, Poping from second stack is similar to Dequeue operation on queue. 1 1 replyShare saurabh rai commented Oct 5, 2016 reply Follow flag ok but that is not my doubt my doubt is rather than popping each elament can we pop until that stack contains 1 element ....is this approach gives same result?? 0 0 replyShare mcjoshi commented Oct 5, 2016 reply Follow flag What do you do with each element that you pop ? store in other stack or discard them 1 1 replyShare saurabh rai commented Oct 5, 2016 reply Follow flag it is obvious store in other stack. 0 0 replyShare mcjoshi commented Oct 5, 2016 reply Follow flag Means pop all first and store then in second one( you will lose elements), while pop one store in second approach gives correct answer. 1 1 replyShare Lakshman Bhaiya commented Apr 8, 2018 reply Follow flag @ mcjoshi Let suppose Stack1 for Push(x) (Enqueue) and Stack2 for Pop() (Dequeue) operation. If I Push all element in Stack1 and Stack2 is empty then I Pop() one by one element from Stack1 and Push(x) into the Stack2.And then Pop() one by one from Stack2. This is good or not? Please correct me if I'm wrong. 0 0 replyShare Please log in or register to add a comment.