Introduction and use of c ++ stack and queue

Source: Internet
Author: User

Introduction and use of c ++ stack and queue

When using the stack and queue of the standard library, the relevant header files are included first.

# Include

# Include

The stack definition is as follows:

Stack Stk;

Define a queue as follows:

Queue Q;

Stack provides the following operations:

S. empty () returns true if the stack is empty; otherwise, falses is returned. size () returns the number of elements in the stack s. pop () deletes the top element of the stack but does not return its value s. top () returns the element at the top of the stack, but does not delete the element s. push () pushes new elements to the top of the stack

The queue provides the following operations:

 

Q. empty () returns true if the queue is empty; otherwise, falseq is returned. size () returns the number of elements in the queue q. pop () deletes the first element of the queue without returning its value q. front () returns the value of the first element, but does not delete this element q. push () new element q at the end of the team. back () returns the value of the end element of the queue, but does not delete this element.

 

C ++ stack)

 

It is an adaptation of a container and implements an advanced and post-output data structure (FILO)

# Include Header file;

The sample code for defining a stack object is as follows:

Stack S1;

Stack S2;

Basic stack operations include:

1. Stack entry: for example, s. push (x );

2. Out-of-Stack: for example, s. pop (). Note: The out-of-stack operation only deletes the element at the top of the stack and does not return this element.

3. Access stack top: such as s. top ();

4. Stack null judgment: for example, s. empty (). If the stack is empty, true is returned.

5. Number of elements in the access stack, such as s. size ();

The following is a simple example:

# Include
 
  
# Include
  
   
Using namespace std; int main (void) {stack
   
    
S; // define a stack for (int I = 0; I <10; I ++) s. push (I); while (! S. empty () {printf ("% lf \ n", s. top (); s. pop () ;}cout <"number of elements in the stack:" <
    
     
Stack definition: A stack is a linear table that is only inserted or deleted at the end of the table. Therefore, the end of the table becomes the top of the stack, and the header becomes the bottom of the stack, A stack without any elements is called an empty stack. Stack modification follows the principle of "back-to-first-out". Therefore, the stack is also called a linear table (LIFO) structure. The stack generally uses arrays as its storage structure, which can avoid using pointers and simplify the program. Of course, the array needs to declare the size of the static data zone in advance, but this is not a problem, it is not difficult to reserve a large enough space for the stack but not to occupy too much space, even if the stack is frequently operated in and out of the stack, if you cannot do this, the method to save memory is to use the linked list storage stack. Basic stack operations for linear tables
     
# Include
      
       
# Include
       
        
Using namespace std; typedef struct Stacknode // defines the struct {int data; // data domain Stacknode * next; // pointer domain of the next node} Stacknode, * Stack; // initialize a chain Stack (return the first node of a chain Stack) stack InitStack () {Stack = (stack) malloc (sizeof (Stacknode )); stack-> next = NULL; return stack;} // Stack void Push (stack, int newData) {// determines whether it is NULL if (stack = NULL) {printf ("stack not initialized, please use \ n" after initialization); return;} // find the last node Stacknode * lastnode = stack; while (lastn Ode-> next) {lastnode = lastnode-> next;} lastnode-> next = (Stacknode *) malloc (sizeof (Stacknode *)); lastnode-> next-> data = newData; lastnode-> next = NULL; printf ("Stack entry successful! \ N ") ;}/// the output Stack int Pop (stack Stack stack) {// judge whether the Stack is empty if (! Stack-> next) {printf ("stack is empty, unable to exit stack \ n"); return-1; //-1 is just a custom error code} // find the money for the last node one node // tempNode: Stacknode * tempNode = stack for the previous node of the last node; while (tempNode-> next) {tempNode = tempNode-> next;} int data = tempNode-> next-> data; free (tempNode-> next ); tempNode-> next = NULL; return data;} int main () {Stack stack = InitStack (); Push (stack, 3); // 3 Push (stack, 4); // 4-in-stack Push (stack, 5); // 5-in-stack printf ("% d \ n", Pop (stack )); printf ("% d \ n", Pop (stack); printf ("% d \ n", Pop (stack); printf ("% d \ n ", pop (stack); // 4th times out of the stack, should return 0 ;}
       
      
 

C ++ Queue (Queue)

 

The queue template class is defined in Header file.

The queue and stack templates are very similar. The queue templates also need to define two template parameters: Element type, container type, element type, and container type, the default type is dqueue.

The sample code for defining a queue object is as follows:

Queue Q1;

Queue Q2;

Basic queue operations include:

1. Join: for example, q. push (x): connect the x element to the end of the queue;

2. Departure: for example, q. pop () pops up the first element of the queue and does not return the value of the element;

3. first element of the access team: q. front ()

4. Access the team end elements, such as q. back ();

5. Number of elements in the access team, such as q. size ();

Ii. priority queue

In The header file also defines a very useful template class priority_queue (priority queue). The difference between the priority queue and the queue is that the priority queue is not out of the queue in the order of queues, instead, the queue is displayed in the priority order of the elements in the queue (the default is the priority of the large ones, or you can specify your own priority by specifying the operator). By default, the queue is a large heap.

The priority_queue template class has three template parameters: Element type, container type, and comparison operator. The first two can be omitted. The default container is vector, and the default operator is less. That is, small rows are arranged in the front row and large rows are arranged in the back row (when the elements at the end of the sequence are queued ).

The sample code for defining the priority_queue object is as follows:

Priority_queue Q1;

Priority_queue > Q2;

Priority_queue , Greater > Q3; // define a small FIFO order

The basic operations of priority_queue are the same as those of queue.

When Beginners use priority_queue, the most difficult thing is how to define a comparison operator. If it is a basic data type or a class that has already defined a comparison operator, you can directly use the STL less operator and greater operator-the default is to use the less operator, that is, small to the front row, A large team goes out first. If you want to define your own comparison operators, there are multiple methods. Here we will introduce one of them: Reload comparison operators. The priority queue tries to substitute the two elements x and y into the comparison operator (for the less operator, call x Y). If the result is true, x is in front of y, y is in front of x, and x is in front of x.

Let's look at the following simple example:

    #include
      
             #include
       
              #include
        
               using namespace std;      class T      {      public:          int x,y,z;          T(int a,int b,int c):x(a),y(b),z(c)          {          }      };      bool operator<(const T&t1,const T&t2)      {          return t1.z
         
          q;          q.push(T(4,4,3));          q.push(T(2,2,5));          q.push(T(1,5,4));          q.push(T(3,3,6));          while(!q.empty())          {              T t=q.top();              q.pop();              cout<
          
         
        
       
      

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.