基础数据结构--队列链表实现

代码已经过测试

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

//元素类型定义
typedef int elemType;

//队列链表节点
typedef struct qNode
{
	elemType data;
	struct qNode *next;
}qNode;

//队列链表
typedef struct qList
{
	qNode *front;
	qNode *rear;
}qList;

//建立队列
qList* createQList()
{
	qList *q = (qList*)malloc(sizeof(qList));
	if(!q) exit(-1);
	q->front = NULL;
	q->rear = NULL;
	return q;
}

//清空队列
int clearQList(qList *&q)
{
	if(!q) return -1;
	if(!q->front || !q->rear) return 0;
	qNode *temp = q->front;
	qNode *dropNode = NULL;
	while(temp != q->rear)
	{
		dropNode = temp;
		temp = temp->next;
		free(dropNode);
	}
	free(temp);
	temp = NULL;
	q->front = NULL;
	q->rear = NULL;
	return 1;
}

//销毁队列
void destroyQList(qList *&q)
{
	if(!q) return ;
	clearQList(q);
	free(q);
	q = NULL;
}

//向队列尾部加节点
int enQList(qList *&q, elemType e)
{
	if(!q) return -1;
	qNode *newNode = (qNode*)malloc(sizeof(qNode));
	if(!newNode)
	{
		return -1;
	}
	newNode->data = e;
	newNode->next = NULL;
	if(q->rear)
	{
		q->rear->next = newNode;
		q->rear = newNode;
	}
	else
	{
		q->front = q->rear = newNode;
	}
	return 1;
}

//在队列头部删减节点
int deQList(qList *&q, elemType &e)
{
	if(!q || !q->front || !q->rear) return -1;
	qNode *dropNode = q->front;
	e = dropNode->data;
	q->front = q->front->next;
	if(dropNode == q->rear)
		q->rear = NULL;
	free(dropNode);
	dropNode = NULL;
	return 1;
}

//打印队列
void showQList(qList *q)
{
	if(!q)
	{
		printf("error: no queue!\n");
		return;
	}
	if(!q->front || !q->rear)
	{
		printf("empty list!\n");
		return ;
	}
	qNode *temp = q->front;
	while(temp != q->rear)
	{
		printf("%d ",temp->data);
		temp = temp->next;
	}
	printf("%d\n",temp->data);
}

//测试代码
int main()
{
	qList *q = createQList();
	enQList(q,34);
	enQList(q,396);
	enQList(q,414);
	enQList(q,5);
	enQList(q,6577);
	enQList(q,1);
	showQList(q);

	elemType e=0;
	deQList(q,e);
	printf("e: %d\n",e);
	showQList(q);

	clearQList(q);
	showQList(q);

	destroyQList(q);
	showQList(q);

	getchar();
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值