数据结构-链队列基本操作

随便写写。

#include<stdio.h>
#include<stdlib.h>
typedef struct QNode {
	int data;
	struct QNode *next;
}QNode,*QueuePtr;
typedef struct{
	QueuePtr front;
    QueuePtr rear;

}LinkQueue;
//初始化
int InitQueue(LinkQueue &Q) {
	Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));
	if (!Q.front) {
		printf("空间开辟失败\n");
		return 0;
	}
	Q.front->next = NULL;
}
//销毁队列
void DestoryQueue(LinkQueue &Q) {
	while (Q.front) {
		Q.rear = Q.front->next;
		free(Q.front);
		Q.front = Q.rear;
	}
	printf("销毁成功\n");
}
//插入
int EnQueue(LinkQueue &Q,int e) {
	QueuePtr q;
	q = (QueuePtr)malloc(sizeof(QNode));
	if (!q) {
		return 0;
	}
	q->data = e;
	q->next = NULL;
	Q.rear->next = q;
	Q.rear = q;
}
//删除
void DeQueue(LinkQueue &Q) {
	if (Q.front == Q.rear) {
		printf("队列为空\n");
	}
	QueuePtr p;
	p = (QueuePtr)malloc(sizeof(QNode));
	p = Q.front->next;
	Q.front->next = p->next;
	if (Q.rear == p) {
		Q.front == Q.rear;
	}
}
//遍历
void QueueTraverse(LinkQueue Q) {
	QueuePtr p;
	p = (QueuePtr)malloc(sizeof(QNode));
	if (Q.front == Q.rear) {
		printf("队列为空\n");
	}
	else {
		p = Q.front->next;
		while (p) {
			printf(" %d", p->data);
			p = p->next;
		}
		printf("\n");
	}
}
int main() {
	LinkQueue Q;
	InitQueue(Q);
	for (int i = 0; i < 4; i++) {
		EnQueue(Q, i);
	}
	QueueTraverse(Q);
	DeQueue(Q);
	QueueTraverse(Q);
	DestoryQueue(Q);
	QueueTraverse(Q);
	return 0;
}

=======================分割线==========================

补发一个循环队列

#include<stdio.h>
#include<stdlib.h>
int max = 100;
typedef struct {
	int *base;
	int rear;
	int front;
}SqQueue;
//初始化
void InitQueue(SqQueue &Q) {
	Q.base = (int *)malloc(max * sizeof(int));
	if (!Q.base) {
		printf("空间开辟失败\n");
	}
	else {
		Q.front = Q.rear = 0;
	}
}
unsigned int QueueLength(SqQueue &Q) {
	return (Q.rear - Q.front);
}
int EnQueue(SqQueue &Q,int e) {
	if ((Q.rear + 1) % max == Q.front) {
		return 0;
	}
	Q.base[Q.rear] = e;
	Q.rear = (Q.rear + 1) % max;
}

void DeQueue(SqQueue &Q) {
	if (Q.front != Q.rear) {
		Q.front = (Q.front + 1) % max;
	}
	}
void TravelQueue(SqQueue &Q) {
	int i=Q.front;
	if (Q.front == Q.rear) {
		printf("循环队列为空\n");
	}
	else {
		for (i; i <Q.rear; i++) {
			printf(" %d", Q.base[i]);
		}
		printf("\n");
	}
}
int main() {
	SqQueue Q;
	InitQueue(Q);
	for (int i = 0; i < 4; i++) {
		EnQueue(Q, i);
	}
	TravelQueue(Q);
	DeQueue(Q);
	TravelQueue(Q);
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值