Use C++ to implement the queue program code
- 2020-04-02 00:58:02
- OfStack
C++ to achieve the queue, if there are shortcomings, also hope to correct
//Myqueue.cpp: defines the entry point for the console application.
//Implement a chained queue, including a header. Queue operations include pop at the end of the queue, push at the end of the queue,
//Get the team head element (front_element), the team tail element (back_element), the number of queue elements (size),
//Whether the queue is empty (empty).
#include "stdafx.h"
#include <iostream>
using namespace std;
//Defines the node structure of the queue
template <class T>
struct NODE
{
NODE<T>* next;
T data;
};
template <class T>
class MyQueue
{
public:
MyQueue()
{
NODE<T>* p = new NODE<T>;
if (NULL == p)
{
cout << "Failed to malloc the node." << endl;
}
p->data = NULL;
p->next = NULL;
front = p;
rear = p;
}
//Join at the back of the line
void push(T e)
{
NODE<T>* p = new NODE<T>;
if (NULL == p)
{
cout << "Failed to malloc the node." << endl;
}
p->data = e;
p->next = NULL;
rear->next = p;
rear = p;
}
//At the head of the team
T pop()
{
T e;
if (front == rear)
{
cout << "The queue is empty." << endl;
return NULL;
}
else
{
NODE<T>* p = front->next;
front->next = p->next;
e = p->data;
//Notice that when there is only one element and it is removed, the node that rear points to is removed
//It should point to the header
if (rear == p)
{
rear = front;
}
delete p; p = NULL;
return e;
}
}
//Gets the queue head element
T front_element()
{
if (front == rear)
{
cout << "The queue is empty." << endl;
return NULL;
}
else
{
NODE<T>* p = front->next;
return p->data;
}
}
T back_element()
{
if (front == rear)
{
cout << "The queue is empty." << endl;
return NULL;
}
else
{
return rear->data;
}
}
//Gets the number of queue elements
int size()
{
int count(0);
NODE<T>* p = front;
while (p != rear)
{
p = p->next;
count++;
}
return count;
}
//Determines if the queue is empty
bool empty()
{
if (front == rear)
{
return true;
}
else
{
return false;
}
}
private:
NODE<T>* front; //Pointer to the header. The front -> Next -> Data is the first element in the header.
NODE<T>* rear;//Pointer to the end of the queue (the last element added)
};
int _tmain(int argc, _TCHAR* argv[])
{
MyQueue<int> myqueue;
cout << myqueue.size() << endl;
myqueue.push(10);
myqueue.push(20);
myqueue.push(30);
cout << myqueue.front_element() << endl;
cout << myqueue.back_element() << endl;
myqueue.pop();
if (myqueue.empty())
{
cout << "The queue is empty now." << endl;
}
else
{
cout << "The queue has " << myqueue.size() << " elements now." << endl;
}
myqueue.pop();
myqueue.pop();
if (myqueue.empty())
{
cout << "The queue is empty now." << endl;
}
else
{
cout << "The queue has " << myqueue.size() << " elements now." << endl;
}
return 0;
}