数据结构——队列之链式存储

数据结构——队列之链式存储

             队列的链式存储道理跟线性表一样,但是需要另外设定两个指针,一个指向队首、一个指向队尾:

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
/**队列的链式存储**/
typedef struct Data{
	char name[10];
	int age;
};
typedef struct Queue{
	Data data;
	Queue *front;	//指向队首元素
	Queue *next;	//指向下一个元素
	Queue *rear;	//指向队尾元素
};
/**初始化空队列**/
void InitQueue(Queue *Q){
	Q->front = Q->rear = Q->next = NULL;
}
/**判断是否为空队列**/
int QueueEmpty(Queue Q){
	//为空返回1否则返回0
	if(Q.front==NULL) return 1;
	else return 0;
}
/**返回队首元素**/
int GetFront(Queue Q,Data *d){
	if(QueueEmpty(Q)==1){
		printf("It's an empty stack!\n");
		return 0;
	}else{
		strcpy(d->name,Q.front->data.name);
		d->age = Q.front->data.age;
		return 1;
	}
}
/**从队尾插入新元素 入队**/
void PushQueue(Queue *Q,Data d){
	Queue* p = (Queue *)malloc(sizeof(Queue));
	strcpy(p->data.name,d.name);
	p->data.age = d.age;
	p->rear = NULL;
	p->next = NULL;
	if(QueueEmpty(*Q)==1){
		Q->front = p;
		Q->rear = p;
	}else{
		Q->rear->next = p;
		Q->rear = p;
	}
}
/**从队首删除元素 出队**/
void PopQueue(Queue *Q,Data *d){
	if(QueueEmpty(*Q)==1){
		printf("It's an empty stack!\n");
	}else{
		Queue *p = Q->front;
		Q->front = p->next;
		strcpy(d->name,p->data.name);
		d->age = p->data.age;
	}
}
/**清空队列**/
void ClearQueue(Queue *Q){
	if(QueueEmpty(*Q)==1){
		printf("It's already an empty stack!\n");
	}else{
		Q->front = Q->next = Q->rear = NULL;
	}
}
/**打印栈内信息**/
void PrintQueue(Queue Q){
	if(QueueEmpty(Q)==1){
		printf("It's an empty stack!\n");
	}else{
		printf("name----age\n");
		Queue *p = Q.front;
		printf("%s    %d\n",p->data.name,p->data.age);
		while(p->next!=NULL){
			printf("%s    %d\n",p->next->data.name,p->next->data.age);
			p = p->next;
		}
	}
}
void main(){
	Data d;
	char name[10];
	int code;
	int age;
	int i=1;
	Queue Q;
	while(i){
		printf("1、初始化空队列\t2、入队\t3、出队\t4、队首元素5、清空队6、打印信息\n");
		scanf("%d",&i);
		switch (i){
			case 1:
				InitQueue(&Q);
				break;
			case 2:
				printf("Input the name: ");
				scanf("%s",&d.name);
				printf("Input the age: ");
				scanf("%d",&d.age);
				PushQueue(&Q,d);
				break;
			case 3:
				PopQueue(&Q,&d);
				printf("Deleted (%s,%d)\n",d.name,d.age);
				break;
			case 4:
				code = GetFront(Q,&d);
				if(code) printf("Top element is (%s,%d)\n",d.name,d.age);
				break;
			case 5:
				ClearQueue(&Q);
				break;
			case 6:
				PrintQueue(Q);
				break;
			default:
				break;
		}
	}
	system("pause");
}


  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小黄鸭and小黑鸭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值