#define _CRT_SECURE_NO_WARNINGS 1
//链队列
#include <stdio.h>
#include <stdlib.h>
typedef int Elemtype;
typedef struct Node
{
Elemtype data;
struct Node* next;
}QueueNode;
typedef struct
{
QueueNode* front, * rear;
}LinkQueue;
//初始化
void Init(LinkQueue* Q)
{
QueueNode* p;
p = (QueueNode*)malloc(sizeof(QueueNode));
p->next = NULL;
Q->front = Q->rear = p;
}
//判断队列是否为空,为空返回真1,不为空返回假0
int Empty(LinkQueue Q)
{
if (Q.front == Q.rear)
{
return 1;
}
return 0;
}
//求队列长度
int GetLength(LinkQueue Q)
{
QueueNode* p;
p = Q.front;
int length = 0;
while (p->next)
{
length++;
p = p->next;
}
return length;
}
//入队操作
void EnQueue(LinkQueue* Q, Elemtype x)
{
QueueNode* p;
p = (QueueNode*)malloc(sizeof(QueueNode));
if (!p) {
printf("内存分配失败\n\n");
return;
}
p->data = x;
p->next = NULL;
Q->rear->next = p;
Q->rear = p;
}
//获取队首元素
Elemtype GetTop(LinkQueue Q)
{
if (Empty(Q))
{
printf("队列为空,无法获取队首元素\n\n");
return 0;
}
int e;
e = Q.front->next->data;
return e;
}
//出队操作
void DeQueue(LinkQueue* Q, Elemtype* e)
{
if (Empty(*Q))
{
printf("当前队列为空,无法执行出队操作\n\n");
return;
}
QueueNode* p;
p = Q->front->next;
if (p == Q->rear)
{
Q->front = Q->rear;
}
*e = p->data;
Q->front->next = p->next;
free(p);
}
int main()
{
LinkQueue Q;
int i, n, e;
Init(&Q);
printf("请输入入队个数: ");
scanf("%d", &n);
printf("\n入队的元素: ");
for (i = 0; i < n; i++)
{
scanf("%d", &e);
EnQueue(&Q, e);
}
printf("队列的长度: %d\n", GetLength(Q));
printf("队列的队首是: %d\n", GetTop(Q));
printf("请输入出队的个数: ");
scanf("%d", &n);
printf("出队的元素有: ");
for (i = 0; i < n; i++)
{
DeQueue(&Q, &e);
printf("%d ", e);
}
return 0;
}
数据结构--链队列
最新推荐文章于 2024-09-11 02:02:22 发布