Two stack implementation queue two queue implementation stack problem, online has a lot of information. Here is just a description of how the method of operation feels at least.
Two stacks to implement a queue
Thought: Suppose that two stacks are s1,s2 respectively. S1 to the queue, when the team, first infer whether S2 is empty, assuming that the S1 element is pressed into the S2 and pop up the topmost element, assuming not, then directly pop up s2 the topmost element.
<span style= "FONT-SIZE:18PX;" >enqueue (s1,s2,k) {push (s1,k) </span><span style= "font-family:arial, Helvetica, Sans-serif;" ><span style= "FONT-SIZE:18PX;" >;</span></span><span style= "FONT-SIZE:18PX;" >}//out Team Dequeue (S1,S2) {if (Isemptystack (S2)) {while (Sizeofstack (S1)!=0) {push (S2,pop (S1));}} if (Isemptystack (s2)) {printf ("stack Overflow");} return pop (s2);} </span>
two queues to implement a stack
Thought: A queue is used to stack Q1. There is also a Q2 as a transit station. On the non-empty queue to the stack and the stack operation, the stack will be directly queued. When the stack is out, the n-1 elements in the queue are first pressed into the broker, and the last element is out of the team
<span style= "FONT-SIZE:18PX;" >push (q1,q2,k) {if (Isemptyqueue (Q1)) {EnQueue (q2,k);} Else{enqueue (q1,k);}} </span>
The stack requires two temporary pointers pushtmp and TMP as the stack and the broker (the method consumes space)
<span style= "FONT-SIZE:18PX;" >pop (Q1,Q2) {Queue pushtmp,tmp;if (Isemptyqueue (Q1)) {pushtmp=q2;tmp=q1;} ELSE{PUSHTMP=Q1;TMP=Q2;} if (Isemptyqueue (pushtmp)) {printf ("OverFlow");} Else{while (sizeof (PUSHTMP)!=1) DeQueue (Tmp,dequeue (pushtmp));} Return Dequeue (pushtmp);} </span>
Copyright notice: This article blog original article. Blogs, without consent, may not be reproduced.
Two stacks implement a queue and a stack of two queues implement the "Introduction to algorithmic topics"