C++でキューを実現するプログラムコード
C++を実現し、足りないところがあれば、
// MyQueue.cpp : 。
// (queue), 。 (pop)、 (push)、
// (front_element)、 (back_element)、 (size)、
// (empty)。
#include "stdafx.h"
#include <iostream>
using namespace std;
//
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;
}
//
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;
}
//
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;
// , ,rear node
//
if (rear == p)
{
rear = front;
}
delete p; p = NULL;
return e;
}
}
//
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;
}
}
//
int size()
{
int count(0);
NODE<T>* p = front;
while (p != rear)
{
p = p->next;
count++;
}
return count;
}
//
bool empty()
{
if (front == rear)
{
return true;
}
else
{
return false;
}
}
private:
NODE<T>* front; // 。 front->next->data 。
NODE<T>* rear;// ( )
};
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;
}
を指摘してください。