王道数据结构:队列顺序存储和链式存储以及基本操作的实现(C语言版)

队列

队列也是一种操作受限的线性表,只允许在表的一端进行插入,而在表的另一端进行删除,操作特性为先进先出。

循环队列顺序存储的实现代码:

#include<stdio.h>
#include<stdlib.h>
#define MaxSize 10
typedef struct {
	int data[MaxSize];
	int front,rear;
}SqQueue;
void InitQueue(SqQueue &Q){
	Q.front=Q.rear=0;
	for(int i=0;i<MaxSize;i++){
		Q.data[i]=0;
	}
	printf("初始化完毕");
} 
bool isEmpty(SqQueue Q){
	if(Q.rear==Q.front) {
		printf("队列空\n");
		return true;
	}else{
		printf("队列不空\n");
		return false;
	}
}
bool EnQueue(SqQueue &Q,int x){
	if((Q.rear+1)%MaxSize==Q.front) return false;//队满
	Q.data[Q.rear]=x;
	Q.rear=(Q.rear+1)%MaxSize;//队尾指针加1取模 
	printf("入队成功\n"); 
	return true; 
}
bool DeQueue(SqQueue &Q,int &x){
	if(Q.rear==Q.front) return false;//队空,报错 
	x=Q.data[Q.front];
	Q.data[Q.front]=0;
	Q.front=(Q.front+1)%MaxSize;//队头指针加1取模 
	printf("出队成功,出队元素值为:%d\n",x);
	return true; 
} 
void PrintQueue(SqQueue s){
	for(int i=0;i<MaxSize;i++){
		printf("%d  ",s.data[i]);
	}
	printf("\n");
}
int main(){
	SqQueue sq;
	InitQueue(sq);
	isEmpty(sq);
	PrintQueue(sq);
	EnQueue(sq,1);
	EnQueue(sq,2);
	EnQueue(sq,3);
	isEmpty(sq);
	PrintQueue(sq);
	int x;
	DeQueue(sq,x);
	PrintQueue(sq);
	 
} 

运行代码截图:

链式队列的实现代码:

#include <stdio.h>
#include <stdlib.h>
typedef struct LinkNode{
	int data;
	struct LinkNode *next;
}LinkNode;
typedef struct {
	LinkNode *front,*rear;
}LinkQueue;
//初始化 
void InitQueue(LinkQueue &Q){
	Q.front=Q.rear=(LinkNode*)malloc(sizeof(LinkNode));
	Q.front->next=NULL;
}
//判队空
bool IsEmpty(LinkQueue Q){
	if(Q.front==Q.rear) {
		printf("队空\n");
		return true;
		 
	}else{
		printf("队不空\n");
		return false;
	}
} 
//入队
void EnQueue(LinkQueue &L,int x){
	LinkNode *s=(LinkNode*)malloc(sizeof(LinkNode));
	s->data=x;
	s->next=NULL;
	L.rear->next=s;//将新节点入队 
	L.rear=s;// 将尾指针后移	 
} 

bool DeQueue(LinkQueue &L,int &x){
	if(L.front==L.rear) return false;//空队 
	LinkNode *p=L.front->next;//查到队头元素
	x=p->data;
	L.front->next=p->next;
	if(p==L.rear){
		L.front=L.rear;
	} 
	free(p);
	return true;
} 
void PrintQueue(LinkQueue &L){
	
	LinkNode *p=L.front->next;
	while(p!=NULL){
		printf("  %d",p->data);
		p=p->next;
	}
	printf("\n");
}
int main(){
	LinkQueue p;
	InitQueue(p);
	IsEmpty(p);
	EnQueue(p,1);
	EnQueue(p,2);
	EnQueue(p,3);
	EnQueue(p,4);
	IsEmpty(p);
	PrintQueue(p);
	int x=0;
	DeQueue(p,x);
	PrintQueue(p);
	EnQueue(p,5);
	PrintQueue(p);
	 
}

 运行代码截图:

发布了90 篇原创文章 · 获赞 36 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_37716512/article/details/104079322