/*用单向链表构造队列的类,实现队列的插入/删除/查看等基本功能
* 队列的特点:先进先出(FIFO)
*/
#include <iostream>
using namespace std;
template <typename T>
class Queue {
struct Node {
Node(const T& d, Node* n) : data(d), next(n) { }
T data;
Node* next;
};
public:
Queue() : header(NULL), len(0) { }
//析构函数,保证删除每一个节点
~Queue()
{
Node* p = header;
while (p != NULL) {
Node* t = p;
p = p->next;
delete t;
}
}
//入队操作,每次入队,将数据加入队尾
void push(const T& value)
{
header = new Node(value, header);
len++;
}
//出队操作,每次出队即删除第一个元素
void pop()
{
if (header == NULL) {
return ;
}
Node* prev = NULL;
Node* curr = header;
while (curr->next != NULL) {
prev = curr;
curr = curr->next;
}
if (prev != NULL) {
prev->next = NULL;
} else {
header = NULL;
}
delete curr;
len--;
}
//查看队首(因为链表用尾插法,链表的尾是队列的头)
T& front()
{
Node* p = header;
while (p->next != NULL) {
p = p->next;
}
return p->data;
}
//查看队尾(因为链表用尾插法,链表的头是队列的尾)
T& back()
{
return header->data;
}
//查看队列长度
int size()
{
return len;
}
//判断队列是否为空,是返回true(1)
bool empty()
{
return len == 0;
}
private:
Node* header;
int len;
};
int main()
{
//对模板采取int作为例子
Queue<int> q;
q.push(5);
q.push(3);
q.push(7);
cout << "front : " << q.front() << endl;
cout << "back : " << q.back() << endl;
cout << "size : " << q.size() << endl;
q.pop();
cout << "----------------" << endl;
cout << "front : " << q.front() << endl;
cout << "back : " << q.back() << endl;
cout << "size : " << q.size() << endl;
cout << "empty : " << q.empty() << endl;
}
* 队列的特点:先进先出(FIFO)
*/
#include <iostream>
using namespace std;
template <typename T>
class Queue {
struct Node {
Node(const T& d, Node* n) : data(d), next(n) { }
T data;
Node* next;
};
public:
Queue() : header(NULL), len(0) { }
//析构函数,保证删除每一个节点
~Queue()
{
Node* p = header;
while (p != NULL) {
Node* t = p;
p = p->next;
delete t;
}
}
//入队操作,每次入队,将数据加入队尾
void push(const T& value)
{
header = new Node(value, header);
len++;
}
//出队操作,每次出队即删除第一个元素
void pop()
{
if (header == NULL) {
return ;
}
Node* prev = NULL;
Node* curr = header;
while (curr->next != NULL) {
prev = curr;
curr = curr->next;
}
if (prev != NULL) {
prev->next = NULL;
} else {
header = NULL;
}
delete curr;
len--;
}
//查看队首(因为链表用尾插法,链表的尾是队列的头)
T& front()
{
Node* p = header;
while (p->next != NULL) {
p = p->next;
}
return p->data;
}
//查看队尾(因为链表用尾插法,链表的头是队列的尾)
T& back()
{
return header->data;
}
//查看队列长度
int size()
{
return len;
}
//判断队列是否为空,是返回true(1)
bool empty()
{
return len == 0;
}
private:
Node* header;
int len;
};
int main()
{
//对模板采取int作为例子
Queue<int> q;
q.push(5);
q.push(3);
q.push(7);
cout << "front : " << q.front() << endl;
cout << "back : " << q.back() << endl;
cout << "size : " << q.size() << endl;
q.pop();
cout << "----------------" << endl;
cout << "front : " << q.front() << endl;
cout << "back : " << q.back() << endl;
cout << "size : " << q.size() << endl;
cout << "empty : " << q.empty() << endl;
}