数据结构(C语言):链式队列的创建、入队、出队、销毁等操作

queue.h

#ifndef _QUEUE_H_
#define _QUEUE_H_

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

typedef int DataType;

typedef struct node
{
	DataType data;
	struct node *pNext;
}QueueNode;

typedef struct list
{
	QueueNode *pFront;
	QueueNode *pRear;
	int cLen;
}QueueList;



extern QueueList *createQueueList();
extern int isEmptyQueue(QueueList *pList);
extern void showQueue(QueueList *pList);
extern int enterQueue(QueueList *pList,DataType data);
extern int outQueue(QueueList *pList,DataType *poutdata);
extern void destroyQueue(QueueList **pList);


#endif

queue.c

#include "queue.h"

/*创建队列*/
QueueList *createQueueList()
{
	QueueList *pList = malloc(sizeof(QueueList));
	if(NULL == pList)
	{
		perror("createQueueList malloc error!\n");
		return NULL;
	}
	pList->pFront = NULL;
	pList->pRear = NULL;
	pList->cLen;

	return pList;
}

/*判空*/
int isEmptyQueue(QueueList *pList)
{
	return 0 == pList->cLen;
}

/*遍历打印(验证)*/
void showQueue(QueueList *pList)
{
	QueueNode *pTmpNode = pList->pFront;
	while(pTmpNode != NULL)
	{
		printf("%d ",pTmpNode->data);
		pTmpNode = pTmpNode->pNext;
	}
	printf("\n");
}

/*入队(尾插)*/
int enterQueue(QueueList *pList,DataType data)
{
	QueueNode *pPushQNode = malloc(sizeof(QueueNode));
	if(NULL == pPushQNode)
	{
		perror("pushQueue malloc error!\n");
		return -1;
	}
	pPushQNode->data = data;
	pPushQNode->pNext = NULL;

	if(isEmptyQueue(pList))
	{
		pList->pFront = pPushQNode;
		pList->pRear = pPushQNode;
	}
	else
	{
		pList->pRear->pNext = pPushQNode;
		pList->pRear = pPushQNode;
	}
	pList->cLen++;

	return 0;
}

/*出队(头删)*/
int outQueue(QueueList *pList,DataType *poutdata)
{
	if(isEmptyQueue(pList))
	{
		return 0;
	}
	QueueNode *pFreeNode = pList->pFront;
	pList->pFront = pFreeNode->pNext;
	if(poutdata != NULL)
	{
		*poutdata = pFreeNode->data;
	}
	free(pFreeNode);
	if(NULL == pList->pFront)
	{
		pList->pRear = NULL;
	}
	pList->cLen--;

	return 0;
}

/*销毁*/
void destroyQueue(QueueList **pList)
{
	while((*pList)->pFront != NULL)
	{
		outQueue(*pList,NULL);
	}
	free(*pList);
	*pList = NULL;
}

main.c

#include "queue.h"

int main(int argc, const char *argv[])
{
	QueueList *pList = NULL;
	pList = createQueueList();

	int i = 0;
	for(i = 1;i < 10;++i)
	{
		enterQueue(pList,i);
	}
	showQueue(pList);

	outQueue(pList,NULL);
	showQueue(pList);
	return 0;
}
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值