The C ++ algorithm uses two stacks to implement a queue
Algorithm ideas:
One stack is used for incoming queues, and one stack is used for outgoing Queues:
There are two stacks s1 and s2; s1 is used to import the stack. For example, if the queue enters 1 2 3 4 4 5, then s1 enters the stack 1 2 3 4 5, And now it needs to exit the queue, it means that 1 should first come out;
Then we extract the data of stack s1 to stack s2, so Stack s2 is 5, 4, 3, 2, and 1. Then, when stack s2 goes out of stack, the result of the queue is simulated;
Write code:
// QueueFrom2Stack. cpp: defines the entry point of the console application. // # Include "stdafx. h" # include
# Include
Using namespace std; template
Class CQueue {public: CQueue (){}~ CQueue () {} void appendTail (const T & node); T deleteHead (); void Prints (); private: stack
S1; stack
S2;}; template
Void CQueue
: AppendTail (const T & node) {s1.push (node); // The inbound stack is the inbound queue} template
T CQueue
: DeleteHead () {if (s2.size () <= 0) // if the stack is empty, first extract s1 from the stack and then press the stack {if (I = 0; I <s1.size (); I ++) {T & data = s1.top (); s1.pop (); s2.push (data) ;}} if (s2.size () = 0) {throw new exception ("queue is empty");} T head = s2.top (); s2.pop (); return head;} template
Void CQueue
: Prints () {while (! S1.empty () {T & data = s1.top (); cout <
Q; q. appendTail (1); q. appendTail (2); q. appendTail (3); q. appendTail (4); q. appendTail (5); q. prints (); getchar (); return 0 ;}