GeeksforGeeks » Interview Questions

Cisco Interview Question for Software Engineer/Developer about Algorithms

(3 posts)
  1. kartik
    Moderator
    Posted 2 years ago #

    Implement Queue using stack. How many stacks you need? Note that you can only use following functions on a queue.

    enQueue() deQueue() isEmpty() isFull()

    And your stack should support following operations.
    push() pop() isEmpty() isFull()

  2. ajaym
    Member
    Posted 2 years ago #

    This can be done using 2 stacks say stack1 and stack2.
    1) enQueue() can be implemented using push() on stack1.
    2) isEmpty() and isFull() will work similar to stack1's isEmpty() and isFull() functions.
    3) deQueue() will be done as following:
    a) pop() all elements from stack1 and push() them in stack2( reversing their order from stack1- LIFO to FIFO).
    b) Use pop() on stack2 to delete that element.
    c) pop() all elements from stack2 and push() them in stack1.

    So now deQueue() operation will cost you O(n) than O(1).

  3. Manoj
    Member
    Posted 11 months ago #

    For deQueue() operation we can do the following,

    if (statck2 isempty())
    {
    a)pop() all elements from stack1 and push() them in stack2
    b)Use pop() on stack2 to delete that element.
    }
    else simply use pop() on statck2.
    

    This will be done in O(1)avg.


Reply

You must log in to post.

RSS feed for this topic