![]() Till now, we have observed that the push operation is costly, but the pop operation takes O(1) time. The front will point to element 3 and the rear will point to element 1, as shown below: Once the elements are popped out from the Queue1, the element 3 will be pushed into the Queue1, and front will point to element 3 as shown below:Īfter pushing element 3 in Queue1, we will pop all the elements from Queue2 and push them back to Queue1. ![]() In order to achieve this, all the elements, i.e., 5 and 1 from the Queue1, will be popped out and added into the Queue2. ![]() Now the next element is 3 which we have to insert in Queue1. In Queue1, the front will point to element 5, and rear will point to element 1, as shown below: Once the insertion of element 5 is completed, element 1 from Queue2 moves back to Queue2. First, we pop the element 1 from the Queue1 and push it into the Queue2, and then we push the element 5 into the Queue1 as shown below:Īs we can observe in the above figure, the front and rear in Queue1 point to element 5, whereas the front and rear in Queue2 point to element 1. First, we push element 1 into the Queue1, so front and rear point to element 1 as shown below:Īfter inserting element 1, we have to insert element 5 into Queue1. In the above, we have created two Queues, i.e., Queue1 and Queue2. Or we can say that we will implement the push and pop operations through Queue.įirst, we create two empty Queues as shown below: In the above list, 'P' means that we have to implement the pop operation whereas, the integers 1, 5, 3, and 2 are to be inserted in the stack. Second, we can make the pop operation costly.įirst approach: Making a push operation costly.First, we can make the push operation costly.There are two approaches to implement stack using Queue: Now, we will discuss how we can implement the Stack using Queue. On the other hand, Queue is a linear data structure that follows the FIFO principle, which means that the added element will be removed first. Next → ← prev Implementation of Stack using QueueĪ stack is a linear data structure that follows the LIFO principle, which means that the element inserted first will be removed last.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |