801 views
3 3 votes

Consider implementation of stack using queue by following algorithm.
Let x be an element to be pushed in the stack.
push(q1, x) {
EQ(q1,x)

while (q1 does not contain 1 element) {
k= DQ(q1)
EQ(q1,k)
}
}
pop(q1) {
DQ(q1)
}
If we implement the above algorithm using linked list, what will be the time complexity for push and pop operations?

  1.   O(n), O(n)
  2.   O(logn), O(1)
  3.   O(1), O(n)
  4.   O(n), O(1)

1 Answer

Best answer
1 1 vote

In the program, Stack is implemented using 1 queue.
Assume, we are keeping two pointers front and rear which points to the head and the tail of the Linked List respectively.

Enqueue a new element at the tail (end) of the linked list and dequeue from the head(front) of the linked list.

Push operation needs O(n), because when push an element in the linked list (queue) we have to move all the previous elements in the linked list to the right of the newly inserted element, and Pop operation will need O(1).
 

Hence, (4) is correct option!

• selected by
Position:
Show:

No related questions found