头文件:
#include<iostream>
using namespace std;
class Queue
{
public:
void put(int item);//在链表结尾插入节点
int get();//取出一个节点
void print();//打印剩余的节点
};
定义成员函数:
#include"queue.h"
#include<iostream>
using namespace std;
struct Data
{
int t;
Data* next;
};
Data* head;
Data* cur = head;//当前
Data* pre;//前一个
int cnt = 0;//用于判断是否是第一次定义链表
void Queue::put(int item)
{
cur = new Data;
cur->t = item;
if (cnt == 0)//head
{
cur->next = NULL;
pre = cur;
head = cur;//第一个节点赋值给head
cnt++;
}
else
{
cur->next = NULL;//当前节点为链表结尾
pre->next = cur;//前一个节点的后继之中指向当前的节点
pre = cur;//当前节点成为前一个节点
}
}
int Queue::get()
{
int result;
for (Data* cur = head; cur != NULL; cur = cur->next)
{
Data* after = cur->next;//当前节点的下一个节点
if (after->next == NULL)//如果下一个节点为链表结尾
{
result = after->t;
cur->next = NULL;//当前节点成为链表结尾
delete after;
}
}
return result;
}
void Queue::print()
{
cout << "栈中剩余 ";
for (Data* cur = head; cur != NULL; cur = cur->next)
{
cout << cur->t;
if (cur->next != NULL)//除了最后一个,其他数字后面都加上‘、’
{
cout << "、";
}
}
cout << endl;
}
调用成员函数:
#include"queue.h"
#include<iostream>
using namespace std;
int main()
{
Queue que;
que.put(10);
que.put(12);
que.put(14);
que.print();
cout << "取出:" << que.get() << ",";
que.print();
cout << "取出:" << que.get() << ",";
que.print();
}