#include<iostream>
using namespace std;
struct Node;
typedef Node* PtrToNode;
typedef PtrToNode LiQueue;
typedef PtrToNode Position;
//队列节点
typedef struct qnode
{
int data;//数据域
struct qnode* next;//指针域
} QNode;
typedef struct Node
{
QNode* front;//队列头部
QNode* rear;//队列尾部
}Node;
//创建队列
LiQueue CreateLiQueue()
{
LiQueue q = (PtrToNode)malloc(sizeof(struct Node));
if (q == NULL)
{
cout << "内存分配失败!" << endl;
//q = NULL;
return q;
}
else
{
q->front = NULL;//将队列的头尾赋值为NULL
q->rear = NULL;
return q;
}
}
//判断队列是否为空
bool isEmpty(LiQueue& q)
{
if (q && q->front == NULL && q->rear == NULL)
return true;
return false;
}
//读入队列当中
void EnQueue(LiQueue& q, int e)
{
QNode* s = NULL;
s = (QNode*)malloc(sizeof(QNode));
if (s == NULL)
{
cout << "分配内存失败" << endl;
}
else
{
s->data = e; //将数据传给s
s->next = NULL;//将s的next指针赋值为NULL
if (q->rear == NULL)//如果是空队列则将数据赋值给头尾
q->front = q->rear = s;
else
{
q->rear->next = s;
q->rear = s;
}
}
}
//将数据弹出列表
int DeQueue(LiQueue& q)
{
int e;
QNode* t;
if (q == NULL) return -1;
t = q->front;
if (q->front == q->rear)//如果是队列中最后一个数据时
q->front = q->rear = NULL;
else
q->front = q->front->next;
e = t->data;
free(t);
return 0;
}
void show(LiQueue& q)
{
qnode* p;//遍历队列的工作指针
p = q->front->next;
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
}
int main()
{
LiQueue q;
q = CreateLiQueue();//创造队列
for (int i = 0; i < 10; i++)
{
EnQueue(q, i);//将数据输入到队列当中
}
show(q);
cout << endl << "弹出后数据:";
DeQueue(q);//弹出队列的数据
show(q);
return 0;
}
用单链表实现队列
最新推荐文章于 2024-08-22 14:28:16 发布