#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
typedef struct LinkNode {
int data;
LinkNode* next;
}LinkNode;
typedef struct{
LinkNode* front,*rear;
}LinkQueue;
//初始化链式队列
bool InitQueue(LinkQueue *Q) {
Q->front=Q->rear=(LinkNode *)malloc(sizeof(LinkNode));
if (Q->front==NULL)
{
return false;
}
Q->front->next=NULL;
return true;
}
//判空
bool QueueEmpty(LinkQueue* Q) {
return Q->front==Q->rear;
}
//入队
bool EnQueue(LinkQueue* Q,int data) {
LinkNode* s = (LinkNode*)malloc(sizeof(LinkNode));
if (s == NULL)
{
return false;
}
s->next= NULL;
s->data = data;
Q->rear->next = s;
Q->rear = s;
return true;
}
//出队
bool DeQueue(LinkQueue* Q, int* a) {
if (QueueEmpty(Q))
{
return false;
}
*a = Q->front->next->data;
LinkNode *p=Q->front->next;
Q->front->next=p->next;
if (Q->rear == p)
{
Q->rear=Q->front;
}
free(p);
return true;
}
int main() {
LinkQueue Q;
if (InitQueue(&Q)) {
printf("Queue initialized successfully.\n");
}
else {
printf("Failed to initialize queue.\n");
return -1;
}
EnQueue(&Q, 1);
EnQueue(&Q, 2);
EnQueue(&Q, 3);
int data;
while (DeQueue(&Q, &data)) {
printf("Dequeued element: %d\n", data);
}
return 0;
}
C语言实现链式队列
最新推荐文章于 2024-11-11 20:03:56 发布