C语言数据结构的循环队列和链队列

两种队列的数据类型定义

循环队列,结构体类型定义如下

typedef struct {
	type data[maxsize];
	type rear;
	type front;
}List;

链队列,结构体定义如下

typedef struct Node{
	type data;
	struct Node *next;
}ListNode;
typedef struct{
	ListNode *rear;
	ListNode *front;
}List;

顺序表和链表不管是存储栈,还是队列等等,优劣势都一样,顺序表存储空间受限但访问方便,链表存储长度随机但访问复杂。

两种队列的初始化

循环队列的初始化是将队尾队首指针都置为0,也可以都置为maxsize-1。
链队列的初始化是将队首指针指向链表开辟的空间,可看作一种另类的头指针。初始化最要注意的是一定最先开辟好空间,不然之后的一切都是白费。

两种队列判断是否为空,是否满的条件

当使用循环队列时,队空的条件

L->rear==L->front

当使用链队列时,队空的条件

p->front == p->rear

可以看出两者本质是一样的,尾指针等于首指针的时候队空,唯一不同点在于L->rear是存储在L所指向空间里的一个变量,作为本空间里数组的下标而存在,p->rear是存储在空间里的指针,指向另一个空间里的链表。有点饶但相信理解这个很重要。
链表可以随时添加节点不存在队满,判断循环队列已满的条件

(L->rear+1)%maxsize==L->front

rear加一取余的目的在于充分的利用空间,循环队列的循环就体现在这里,要完全理解。

附完整代码供大家参照

循环队列

#include<stdio.h>
#include<malloc.h>
#define maxsize 100
#define type int
 
typedef struct {
	type data[maxsize];
	type rear;
	type front;
}List;

int InitList(List *L){
	if(L!=NULL){
		L->rear=L->front=maxsize-1;	
		return 1;
	}
	else 
		return 0;
}

int push(List *L,int n){
	if((L->rear+1)%maxsize==L->front )
		return 0;
	else
	{
		L->rear=(L->rear+1)%maxsize;
		L->data[L->rear ]=n;
		return 1;
	}
}

int pop(List *L,int *n){
	int x;
	if(L->rear==L->front)
		return 0;
	else
	{
		L->front=(L->front+1)%maxsize;
		x=L->data[L->front];
		n=&x;
		printf("\n%d",*n);
		return 1;
	}
}

void print(List *L){
	if((L->rear-L->front+maxsize)%maxsize==0){
		printf("\n队列为空");
	}
	else
	{
		for(int i=0;i<((L->rear-L->front+maxsize)%maxsize);i++)
		printf("%d ",L->data[i]);	
	}
}

int main(){
	List *L;
	L=(List *)malloc(sizeof(List));
	int *n,*m;
	
	InitList(L);
	push(L,1);
	push(L,2);
	print(L);
	pop(L,n);
	pop(L,m);
	print(L);
	return 0;
} 

链队列

#include<stdio.h>
#include<malloc.h>
#define type int 

typedef struct Node{
	type data;
	struct Node *next;
}ListNode;
typedef struct{
	ListNode *rear;
	ListNode *front;
}List;

int InitList(List *p){
	p->front=(ListNode *)malloc(sizeof(ListNode));
	if(p!=NULL){
		p->rear=p->front;
		p->front->next=NULL;
		return 1;
	}
	else
		return 0;
}

int push(List *p,int n){
		ListNode *s;
		s=(ListNode *)malloc(sizeof(ListNode));
		s->data=n;
		s->next=p->rear->next;
		p->rear->next=s;
		printf("添加队尾元素:%d\n",n);
		return 1; 
}

int pop(List *p){

	ListNode *temp;
	//我发现加上这个if语句之后的语句不能运行,希望大家能帮帮我
	//if(p->front == p->rear){
	//	return (0);
	//}
		temp=p->front->next;
		p->front->next=temp->next;
		if(p->rear==temp){
			p->rear=p->front;
		}
		printf("删除队首元素:%d\n",temp->data );
		free(temp); 
}
int main(){
	List *p;

	p=(List *)malloc(sizeof(List));
	
	InitList(p);
	push(p,1);
	push(p,2);
	pop(p);
	pop(p);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44078014/article/details/105000201
今日推荐