The C ++ algorithm uses two stacks to implement a queue

Source: Internet
Author: User

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 ;}
            
           
          
         
        
       
      
     
    
   
  
 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.