动态队列的一些基本操作

//建立动态队列(带头结点) 
/*
相对于静态队列,动态队列不需要考虑长度的限制
而且动态队列就相当于单链表的阉割版 
*/ 
#include<stdio.h>
#include<stdlib.h>
//构建动态队列结点 
typedef struct queuenode{
	int data;                 //数据域 
	struct queuenode* next;   //指针域 
}queueNode;
//构建动态队列
typedef struct linkqueue{
	queueNode* front;         //头指针 
	queueNode* rear;          //尾指针 
}linkQueue;
//初始化
void initiaQueue(linkQueue &Q){
	//建立头结点 
	Q.front = Q.rear = (queueNode*)malloc(sizeof(queueNode));
	if(Q.rear == NULL){
		printf("内存分配失败,无法进行后续操作!\n");
	}
	else{
		Q.rear->next = NULL;
		printf("初始化完毕!\n");
	}
} 
//判断初始化
bool judge(linkQueue &Q){
	if((Q.front == Q.rear)&&(Q.front->next == NULL)){
		printf("初始化成功!\n");
		return true;
	}
	else{
		printf("初始化失败!\n");
		return false;
	}
} 
//求队列的长度
int getLength(linkQueue &Q){
	int len;
	queueNode* N;
	N = Q.front->next;
	len = 0;
	while(N != NULL){
		len++;
		N = N->next;
	}
	return len;
} 
//输出队列内容
void printQueue(linkQueue &Q){
	queueNode* N;
	N = Q.front->next;
	while(N != NULL){
		if(N->next == NULL){
			printf("%d\n",N->data);
		}
		else{
			printf("%d ",N->data);
		}
		N = N->next;
	}
	printf("读取队列内容完毕!\n");
	printf("该队列的长度是%d\n",getLength(Q));
} 
//构建队列
void setQueue(linkQueue &Q){
	int ele;
	queueNode* N;
	printf("请输入你要入队的元素(除数字-1外):\n");
	scanf("%d",&ele);
	while(ele != -1){
		N = (queueNode*)malloc(sizeof(queueNode));
		N->data = ele;
		Q.rear->next = N;
		Q.rear = N;
		printf("%d已成功入队!\n",ele);
		printf("结束创建请输入-1\n");
		scanf("%d",&ele);
	}
	Q.rear->next = NULL;
	printf("创建队列完毕!\n");
	printQueue(Q);
} 
//入队 
void enQueue(linkQueue &Q){
	int ele;
	queueNode* N;
	printf("请输入你要入队的元素:\n");
	scanf("%d",&ele);
	N = (queueNode*)malloc(sizeof(queueNode));
	N->data = ele;
	Q.rear->next = N;
	Q.rear = N;
	Q.rear->next = NULL;
	printf("%d已成功入队!\n",ele);
	printQueue(Q);
}
//出队 
void outQueue(linkQueue &Q){
	int ele;
	queueNode* N;
	if(getLength(Q) == 0){
		printf("此队列为空,无须再进行出队操作了!\n");
	}
	else{
		N = (queueNode*)malloc(sizeof(queueNode));
		N = Q.front->next;
		Q.front->next = Q.front->next->next;
		ele = N->data;
		printf("此次出队的元素是%d\n",ele);
		if(N == Q.rear){
			Q.rear = Q.front;
		}
	}
	printf("出队操作执行完毕!\n");
	printQueue(Q);
	free(N);
} 
//读取队头元素 
int getFront(linkQueue &Q){
	int ele;
	queueNode* N;
	N = (queueNode*)malloc(sizeof(queueNode));
	N = Q.front->next;
	if(N != NULL){
		ele = N->data;
		return ele;
	}
	else{
		printf("此队列为空,无法读到队头元素!\n");
		return 0;
	}
}
int main(){
	int i;
	linkQueue Q;
	initiaQueue(Q);
	judge(Q);
	setQueue(Q);
	for(i=1;i<10;i++){
		outQueue(Q);
	}
	outQueue(Q);
	enQueue(Q);
	enQueue(Q);
	enQueue(Q);
	outQueue(Q);
	printf("此次读取的队头元素是%d\n",getFront(Q));
	return 0;
}
 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值