数据结构之队列链式存储

//链式队列
#include<stdio.h>
#include<stdlib.h>

#define ElemType int

typedef struct LinkNode{//链式队列节点
ElemType data;
struct LinkNode *next;
}LinkNode;

typedef struct{//链式队列
LinkNode *front_queue,*rear_queue;//队列得队头和队尾
}LinkQueue;


void initQueue(LinkQueue *head)
{
printf("初始化\n");
head->front_queue=head->rear_queue=(LinkNode *)malloc(sizeof(LinkNode));
head->front_queue->next=NULL;
}

//判断是否空队列 空返回一
int IsEmpty(LinkQueue head)
{
//printf("判断是否为空\n");
if(head.front_queue==head.rear_queue)
return 1;//空
return 0;
}

//尾插入队
void EnQueue(LinkQueue *tail,ElemType target)
{
//printf("入队\n");
LinkNode *newNode=(LinkNode *)malloc(sizeof(LinkNode));
newNode->data=target;
newNode->next=NULL;

tail->rear_queue->next=newNode;//先将队列连起来 队列尾部加一
tail->rear_queue=newNode;//现在队列最末端是新的节点了,所以再将队列尾指针更新
}

//出队,先进先出
void DeQueue(LinkQueue *front_Queue,ElemType *target)
{
LinkNode *head=front_Queue->front_queue;//不存数据的头节点
printf("出队\n");
//得判断是不是空队列
if(IsEmpty(*front_Queue))
{
printf("目前没有数据\n");
return;//是就退出
}

//常规 因为这个队列是有头节点的,所以取的数据是真正的节点的数据
*target=head->next->data;

//取完数据就是删除了,用真正的节点的下一个节点取代它就完成了
head->next=head->next->next;

//只有一个节点的情况
//如果只有一个节点,那么将next的next赋值给next后只有NULL,而我们在判空函数IsEmpty()的判定中写的是head.front_queue==head.rear_queue 是指针是否相当
//还有就是尾指针的安排,将最后一个节点删除了,那么尾指针也该指到头节点上了
if(front_Queue->rear_queue==head->next)
{
front_Queue->rear_queue=head;//让头尾指针又去指向头节点
}

}

void showQueue(LinkQueue head)
{
LinkNode *pMove=head.front_queue->next;//先进先看
printf("目前队列的元素:\n");
while(pMove)
{
printf("%d ",pMove->data);
pMove=pMove->next;
}
printf("\n");
}

int main()
{
int cot=5;
LinkQueue *head;
initQueue(head);
//得有个指针记录尾指针
LinkQueue *tail=head;

while(cot--)
{
EnQueue(tail,cot);
}
showQueue(*head);

ElemType a;
DeQueue(head,&a);
printf("取出的是%d\n",a);
showQueue(*head);


return 0;
}

posted @ 2022-07-17 21:08  天天掉头发  阅读(25)  评论(0编辑  收藏  举报
返回顶端