C语言创建链队列

一个简单的链队列

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

#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
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值