Implement Stack using Two Queues

后端 未结 23 735
感情败类
感情败类 2020-11-28 17:05

A similar question was asked earlier there, but the question here is the reverse of it, using two queues as a stack. The question...

Given two queues with their sta

23条回答
  •  清酒与你
    2020-11-28 17:58

    Let S1 and S2 be the two Stacks to be used in the implementation of queues.

    struct Stack 
    { struct Queue *Q1;
      struct Queue *Q2;
    }
    

    We make sure that one queue is empty always.

    Push operation : Whichever queue is not empty, insert the element in it.

    • Check whether queue Q1 is empty or not. If Q1 is empty then Enqueue the element in it.
    • Otherwise EnQueue the element into Q1.

    Push (struct Stack *S, int data) { if(isEmptyQueue(S->Q1) EnQueue(S->Q2, data); else EnQueue(S->Q1, data); }

    Time Complexity: O(1)

    Pop Operation: Transfer n-1 elements to other queue and delete last from queue for performing pop operation.

    • If queue Q1 is not empty then transfer n-1 elements from Q1 to Q2 and then, DeQueue the last element of Q1 and return it.
    • If queue Q2 is not empty then transfer n-1 elements from Q2 to Q1 and then, DeQueue the last element of Q2 and return it.

    `

    int Pop(struct Stack *S){
    int i, size;
    if(IsEmptyQueue(S->Q2)) 
    {
    size=size(S->Q1);
    i=0;
    while(iQ2, Dequeue(S->Q1)) ;
      i++;
    }
    return DeQueue(S->Q1);  
    }
    else{
    size=size(S->Q2);
    while(iQ1, Dequeue(S->Q2)) ;
    i++;
    }
    return DeQueue(S->Q2);
    } }
    

    Time Complexity: Running Time of pop Operation is O(n) as each time pop is called, we are transferring all the elements from one queue to oter.

提交回复
热议问题