#include <iostream>
#include <stdio.h>
#include <malloc.h>
using namespace std;
//链式队列结点
typedef struct Node{
int data;
struct Node *next;
}Node;
//队列
typedef struct {
Node *front,*rear;
}LinkQueue;
//初始化
void init(LinkQueue *q){
q->front=(Node*)malloc(sizeof(Node));
if(q->front!=NULL){
q->rear=q->front;
q->front->next=NULL;
}
}
//判空
bool isempty(LinkQueue *q){
if(q->front==q->rear)
return true;
else
return false;
}
//入队
void enqueue(LinkQueue *q,int e){
//创建新结点,插入到链尾
Node *s=(Node *)malloc(sizeof(Node));
s->data=e;
s->next=NULL;
printf("%d 入队成功.\n",e);
q->rear->next=s;
q->rear=s;//修改队尾指针
}
//出队
void dequeque(LinkQueue *q){
if(q->front==q->rear)
printf("empty");
int x;
Node *s=q->front->next;
x = s->data;
printf("%d 出队.\n",x);
q->front->next=s->next;
if(q->rear==s)
q->rear=q->front;//若原队列中只有一个节点,删除后为空
s=NULL;
}
//取队头元素
int gettop(LinkQueue *q){
int x;
if(q->front==q->rear)
return 0;
else
x=q->front->next->data;
return x;
}
//输出
void show(LinkQueue *q){
while(!isempty(q)){
cout<<q->front->next->data<<" ";
q->front->next=q->front->next->next;
}
cout<<endl;
}
int main()
{
LinkQueue q;
LinkQueue *s;
s=&q;
//初始化队列
init(s);
//入队
for(int i=0;i<5;i++)
enqueue(s,i);
//出队
dequeque(s);
//取队头元素
int x = gettop(s);
cout<<"队头元素是:"<<x<<endl;
return 0;
}
队列操作的实现-链式存储
最新推荐文章于 2022-05-26 16:11:50 发布
本文深入探讨了如何使用链式存储结构实现队列操作。从队列的基本概念出发,详细阐述了入队、出队的过程,并通过实例解析了链表节点的添加和删除。同时,讨论了链式队列相较于数组队列的优势,如动态扩容、空间利用率高等特点。
摘要由CSDN通过智能技术生成