您的位置:首页 > 编程语言 > C语言/C++

C语言创建链队列

2020-02-02 07:30 706 查看

一个简单的链队列

有创建队列,入队,出队,输出,统计长度函数

#define ERROR 1
#include<stdio.h>
#include<stdlib.h>
typedef int Data;
typedef struct QNode {
Data data;
struct QNode* next;
}QNode,*QueuePtr;
typedef struct LinkQueue {
QueuePtr front, rear;
}LinkQueue;
int InitQueue(LinkQueue& Q)
{
QueuePtr head = (QueuePtr)malloc(sizeof(QNode));
head->next = NULL;
head->data = NULL;
Q.front = Q.rear = head;
return 0;
}
int EnQueue(LinkQueue& Q)
{
QueuePtr p = (QueuePtr)malloc(sizeof(QNode));
p->next = NULL;
printf("请输入结点数据: ");
scanf_s("%d", &p->data);
Q.rear->next = p;
Q.rear = p;
return 0;
}
int OutQueue(LinkQueue& Q, Data &e)
{
QueuePtr d;
if (Q.front == Q.rear) {
return ERROR;
}
d = Q.front->next;
e = d->data;
Q.front->next = d->next;
if (Q.rear == d) {
Q.rear = Q.front;
}
free(d);
return 0;
}
void GetHead(LinkQueue& Q, Data e)
{
e = Q.front->next->data;
}
void OutputQueue(LinkQueue& Q)
{
QueuePtr p;
p = Q.front->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
}
int check_length(LinkQueue& Q)
{
int length = 0;
QueuePtr p;
p = Q.front;
while (p->next != NULL) {
p = p->next;
length++;
}
return length;
}

下面是用switch做目录的交互界面

int main()
{
int i, e, sl, num;
LinkQueue Q;
do {
printf("请选择功能:\n");
printf("创建一个队列...1\n入队操作...2\n出队并显示队列状态...3\n退出...0\n");
scanf_s("%d", &sl);
switch (sl) {
case 0:exit(0); break;
case 1:InitQueue(Q); system("pause"); system("cls");  break;
case 2:printf("请问需要入队几次?  "); scanf_s("%d", &num);
for (i = 0; i < num; i++) { EnQueue(Q); }
system("pause"); system("cls"); break;
case 3:if (OutQueue(Q, e)) { printf("队列已被清空"); }
else { printf("删除队首 %d;", e); printf("队中还剩余%d个数据:", check_length(Q)); OutputQueue(Q); }
system("pause"); system("cls"); break;
}
} while (1);
return 0;
}

把上面的函数及头文件和下面的main函数复制粘贴就可以直接运行了

  • 点赞 2
  • 收藏
  • 分享
  • 文章举报
某科学的烫烫烫 发布了21 篇原创文章 · 获赞 43 · 访问量 3293 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: