"C + +" uses two stacks to implement a queue (detailed description)

Source: Internet
Author: User

Implement a queue using two stacks


Idea One:

We set the S1 to be in the stack, and the S2 is out of the stack.


into the queue and press it directly to S1.


Out of the queue, first put the elements in the S1 into the S2, pop up S2 the top elements of the stack, and then the remaining elements of S2 back to S1.


650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M01/7E/E7/wKioL1cMpjajUzcyAABT0frZ3KM694.png "title=" N) tc$p %c[ll3~l]z) $XO 15r.png "alt=" Wkiol1cmpjajuzcyaabt0frz3km694.png "/>

Disadvantages:

Every time just out of the stack an element is going to pour the element upside down, trouble!!!



Idea 2:

When entering a queue:
If the S1 is empty, pour all the elements in the S2 into the S1. Otherwise press directly into the S1

When out of the queue:
If the S2 is not empty, the top element of the S2 is ejected directly from the stack. Otherwise, all elements of the S1 are ejected into the S2, and the top elements of the S2 are ejected.


650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M01/7E/E9/wKiom1cMppLwMd0QAAB3LagChFk387.png "title=" [ib$[ Yy$8k~ez4wtzi~{[_y.png "alt=" Wkiom1cmpplwmd0qaab3lagchfk387.png "/>



Train of thought 1 unconditionally each time to pour the elements upside down, thinking 2 out of the team than the idea of 1 simple



Idea 3:

We set the S1 to be in the stack, and S2 is out of the stack.

Into the queue: press the element directly into the S1

Out queue: If S2 is not empty, the top element of the S2 is ejected directly from the stack. Otherwise, all elements of the S1 are ejected into the S2, and the top elements of the S2 are ejected.


650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M02/7E/E7/wKioL1cMp8HR1m6aAABLlSxXUHE848.png "title=" N) tc$p %c[ll3~l]z) $XO 15r.png "alt=" Wkiol1cmp8hr1m6aaabllsxxuhe848.png "/>


Compared to Method 2, the queue can be pressed directly into the ~

So, we can see that the idea of three is the simplest, we look at the code below.


Code implementation:

#define  _CRT_SECURE_NO_WARNINGS 1#include<iostream>using namespace std; #include < assert.h>//directly implement the stack, or you can use the adapter to implement the stack, or use the library. The basic functions of Stack can be realized as follows: Template<class t>class stack{public:    stack ()          :_array (NULL)         ,  _size (0)         , _capacity (0)     {}     Stack<T> (const stack<t>& s)          : _array (new t[s._capacity])     {         swap (_array, s._array);         swap (_size,  s._size);         swap (_capacity, s._capacity);     }    stack<t>& operator= (const stack<t>& s)     {        if  (&s !=  This)         {             swap (_array, s._array);             swap (_size, s._size);             Swap (_capacity, s._capacity);        }         return *this;    }    ~stack ()      {        if  (_array)          {            delete[]  _array;            _array = NULL;      &nbSp;  }    }    void _checkcapacity ()      {        if  (_size == 0)          {            _capacity  = 3;            _array = new  T[_capacity];        }         if  (_size >= _capacity)         {             _capacity *= 2;             T* tmp = new T[_capacity];             for  (Int index = 0; index  < _size; index++)             {                 tmp[index] = _array[index];             }             delete[] _array;             _array = tmp;        }     }    void push (const t& x)     {         _checkcapacity ();         _ Array[_size++] = x;    }    void pop ()      {        if  (_size == 0)          {            return;         }        --_size;    }     size_t size ()     {         Return _size;    }    bool empty ()     {         return size ()  == 0;    }     t& top ()     {         assert (_size > 0);         return _array[_size  - 1];    }private:    T* _array;     size_t _size;    size_t _capacity;}; template<class t>class queue{public:    void inqueue (const t& x)     {         s1. Push (x);     }    void outqueue ()     {         //stack s2 is empty, the stack S1 elements are poured into S2, and then pop the topmost element          if  (S2. Empty ())         {             while  (!s1. Empty ())             {                 s2. Push (S1. Top ());                 s1. Pop ();            }             s2. Pop ();         }        //stack s2 not empty, direct popup element          else        {             s2. Pop ();        }    }         void print ()     //print queue elements in four cases.     {        if  (S1. Empty ()  && s2. Empty ())         {             cout <<  "the queue is empty!";         }        else if   (!S1. Empty ()  && s2. Empty ())         {            while  (!s1. Empty ())             {                 s2. Push (S1. Top ());                 s1. Pop ();            }             while  (!S2. Empty ())             {                 cout << s2. Top ()  <<  "  ";                 s2. Pop ();            }         }        else if  (S1. Empty ()  && !s2. Empty ())         {             while  (!S2. Empty ())             {                 cout << s2. Top ()  <<  "  ";                 s2. Pop ();            }         }        else         {            while  (!S2. Empty ())             {    &nbsP;           cout << s2. Top ()  <<  "  ";                 s2. Pop ();            }             while  (!s1. Empty ())             {                 s2. Push (S1. Top ());                 s1. Pop ();            }             while  (!S2. Empty ())             {          &nbSp;      cout << s2. Top ()  <<  "  ";                 s2. Pop ();            }         }        cout << endl;     }private:    stack<t> s1;    //Queue      stack<t> s2;    //out of the team};//test two stacks to implement a queue void test1 () {     queue<int> q1;    q1. InQueue (1);     q1. InQueue (2);     q1. InQueue (3);     q1. InQueue (4);     /*q1. Print (); */    q1. Outqueue ();     /*q1. Print (); */    q1. InQueue (5);    &Nbsp;q1. InQueue (6);     q1. InQueue (7);     q1. Print ();} Int main () {    test1 ();     system ("Pause");     return 0;}


(One detail):


Note that when you pour an element into another stack, the code is not first pop, then push. Because of this, the element will not be found after push. So first access to top of the stack, then push, then pop.

This article is from the "C language 100-200 Prime" blog, please be sure to keep this source http://10740184.blog.51cto.com/10730184/1763006

"C + +" uses two stacks to implement a queue (detailed description)

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.