C++ with two standard containers stack the implementation of a queue method

  • 2020-04-02 00:57:53
  • OfStack

The code is as follows:

//Stacktoqueue.cpp: defines the entry point for the console application.
//Stack with two standard containers to implement a queue
#include "stdafx.h"
#include <iostream>
#include <stack>
using namespace std;
template <class T>
class StackToQueue
{
public:
 StackToQueue()
 {
  stack1;
  stack2;
 }
 void push(T e)
 {
  while (!stack2.empty())
  {
   T temp;
   temp = stack2.top();
   stack2.pop();
   stack1.push(temp);
  }
  stack2.push(e);
  while (!stack1.empty())
  {
   T temp;
   temp = stack1.top();
   stack1.pop();
   stack2.push(temp);
  }
 }

 void pop()
 {
   stack2.pop();
 }

 T front()
 {
  if (!empty())
  {
   return stack2.top();
  }
  else
  {
   return NULL;
  }
 }
 bool empty()
 {
  return stack2.empty();
 }
 size_t size()
 {
  return stack2.size();
 }
private:
 stack<T> stack1, stack2;
};
int _tmain(int argc, _TCHAR* argv[])
{
 StackToQueue<int> queue;
 int i(0);
 cout << "Enter several integer number,and press ctrl+z to the end." << endl;
 while (cin >> i)
 {
  queue.push(i);
 }
 cout << "The front element is: " << queue.front() << endl;
 cout << "The size now is: " << queue.size() << endl;
 if (!queue.empty())
 {
  cout << "Pop one element now." << endl;
  queue.pop();
 }
 cout << "The front element is: " << queue.front() << endl;
 cout << "The size now is: " << queue.size() << endl;
 return 0;
}

Related articles: