队的顺序存储和链式存储的基本操作实现--随笔记录(5)

这篇博客详细介绍了顺序队和链队两种数据结构在C语言中的基本操作实现,包括初始化、判断队列是否为空、入队、出队、获取队头元素以及计算队列长度。通过示例代码展示了如何使用循环队列处理顺序队的溢出问题,以及链队中通过链表节点进行插入和删除操作。这些是数据结构与算法学习中的基础内容。
摘要由CSDN通过智能技术生成

1、顺序队的基本操作实现代码:

#include <stdio.h>
#include <stdlib.h> 

#define MaxSize 10
typedef int ElemType;
/****
*队 ----对头出队,队尾入队(一段插入,另一端删除) 
**/ 
//定义顺序队的结构 
typedef struct{
	ElemType data[MaxSize] ;
	int front,rear;	//队头指针和队尾指针 
}SqQueue;

//初始化 
void InitQueue(SqQueue &Q){
	Q.front=Q.rear=0;
} 

//判队空--牺牲一个单元来区分队空队满 
bool isEmpty(SqQueue Q){
	if(Q.front==Q.rear){
		return true;
	}else{
		return false;
	}
} 

//入队(循环队列)
bool EnQueue(SqQueue &Q,ElemType value){
	//判队满
	if((Q.rear+1)%MaxSize==Q.front){
		printf("队满!\n");
		return false;
	} 
	Q.data[Q.rear]=value; 
	Q.rear=(Q.rear+1)%MaxSize;//队尾指针加1取模
	return true; 
	
}
//出队(循环队列) 
bool DeQueue(SqQueue &Q,ElemType value) {
	if(Q.front==Q.rear){
		return false;
	}
	value=Q.data[Q.front];
	Q.front=(Q.front+1)%MaxSize;//队头指针加1取模 
	return true; 
}
//求队列长度
int QueueLength(SqQueue Q){
	return (Q.rear+MaxSize-Q.front)%MaxSize;
}
 
//取队头元素
ElemType GetHead(SqQueue Q) {
	if(Q.front==Q.rear){
		return false;
	}
	return Q.data[Q.front];
}
 
int main(){
	SqQueue Q;
	InitQueue(Q);
	ElemType value;
	EnQueue(Q,1);
	EnQueue(Q,2);
	printf("队列的长度为:%d\n",QueueLength(Q));
	printf("队头元素为:%d\n",GetHead(Q));
	DeQueue(Q,value);
	printf("队列的长度为:%d\n",QueueLength(Q));


}

2、链队的基本操作实现代码:

/*带头结点链队的实现*/
#include <stdio.h>
#include <stdlib.h> 

typedef int ElemType;

typedef struct LinkNode{
	ElemType 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){
		return true;
	}else{
		return false;
	}
} 
//入队
bool EnQueue(LinkQueue &Q,ElemType value){
	
	LinkNode *newNode=(LinkNode *)malloc(sizeof(LinkNode));
	newNode->data=value;
	newNode->next=NULL;
	Q.rear->next=newNode;
	Q.rear=newNode;
	return true; 
} 

//出队
bool DeQueue(LinkQueue &Q,ElemType &value){
	if(Q.front=Q.rear){
		return false;
	}
	LinkNode *delNode=Q.front->next;
	value=delNode->data;
	Q.front->next=delNode->next;
	if(Q.rear==delNode){
		Q.rear=Q.front;//若队列中只有一个结点,删除后变空 
	}
	free(delNode) ;
	return true; 
} 
//获取队头元素
ElemType GetHead(LinkQueue Q) {
	if(Q.front==Q.rear){
		return false;
	}
	LinkNode *p=Q.front->next;
	return p->data;
} 
int main(){
	LinkQueue Q;
	InitQueue (Q);
	ElemType value;
	EnQueue(Q,1);
	printf("队头元素为:%d\n",GetHead(Q));
	DeQueue(Q,value);
	printf("队头元素为:%d\n",GetHead(Q));
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值