队列的链式实现
程序员文章站
2022-07-14 13:51:20
...
#include <iostream>
using namespace std;
typedef struct QNode
{
int data;
struct QNode*next;
}QNode,*QueuePtr;
typedef struct
{
QueuePtr front,rear;
}LinkQueue;
void InitQueue(LinkQueue *queue);
void EnQueue(LinkQueue *queue,int e);
void DeQueue(LinkQueue *queue);
void PrintQueue(LinkQueue queue);
int main(void)
{
LinkQueue queue;
InitQueue (&queue);
EnQueue (&queue,5);
EnQueue (&queue,6);
EnQueue (&queue,7);
EnQueue (&queue,8);
EnQueue (&queue,9);
PrintQueue(queue);
DeQueue(&queue);
PrintQueue(queue);
system("pause");
return 0;
}
//入队
void EnQueue(LinkQueue *queue,int e)
{
QueuePtr s;
s = (QNode *)malloc(sizeof(QNode));
s->data = e;
s->next = NULL;
queue->rear->next = s;
queue->rear = s;
}
//出队
void DeQueue(LinkQueue *queue)
{
QueuePtr p;
p = queue->front->next;
queue->front->next = p->next;
if(queue->rear==p)
{
queue->rear=queue->front;
}
free(p);
}
//初始化队列
void InitQueue(LinkQueue *queue)
{
QueuePtr p;
p = (QNode *)malloc(sizeof(QNode));
p->next=NULL;
queue->front=queue->rear=p;
}
//打印
void PrintQueue(LinkQueue queue)
{
QueuePtr p;
for(p=queue.front->next;p;p=p->next)
{
cout<<p->data<<endl;
}
}