链式队列

 

链式队列的基本操作。

在传递参数时,要分清何时一定要对变量取地址,何时可取可不取。

在初始化函数中,由于需要修改主函数中queue指针的指向,为其分配空间,所以传递参数时要对其取地址。同理,在销毁队列的函数中,也需要取地址。

头文件源代码如下:

#ifndef _LINKQUEUE_H
#define _LINKQUEUE_H

#define SUCCESS 10000
#define FAILURE 10001
#define TRUE    10002
#define FALSE   10003

struct node     //表示结点信息
{
	int data;                         //数据域
	struct node *next;                //指针域
};
typedef struct node Node;

struct queue
{
	Node *front;             //队头指针
	Node *rear;              //队尾指针
};
typedef struct queue Q;

int queueinit(Q **q);
int queueinsert(Q*queue, int e);
int DeleteQueue(Q *q);
int GetFirst(Q *q);
int QueueEmpty(Q *q);
int ClearQueue(Q *q);
int QueueDestory(Q **q);
#endif
#include "LinkQueue.h"
#include<stdio.h>
#include<stdlib.h>
int queueinit(Q **q) //初始化
{
	(*q) = (Q *)malloc(sizeof(Q));//存放队列信息,队头和队尾指针
	if((*q) == NULL)
	{
		return FAILURE;
	}
	Node *p=(Node *)malloc(sizeof(Node));//保存结点信息
	if(p == NULL)
	{
		return FAILURE;
	}
	p->next = NULL;
	(*q)->front = (*q)->rear = p;//队头和队尾指针都指向头结点
	return SUCCESS;
}

int queueinsert(Q *queue, int e)//入队
{
	if(NULL == queue)
  	{
   		return FAILURE;
	}

	Node *q= (Node *)malloc(sizeof(Node));//新建结点
	if (NULL == q)
	{
		return FAILURE;
	}

	q->data = e;      //数据域
	q->next = NULL;   //指针域
	queue->rear->next = q;//头结点指针域指向新建的结点
	queue->rear = q;     //队尾指针指向新的结点

	return SUCCESS;
}

int DeleteQueue(Q *q)//删除结点
{
	if (q == NULL || q->rear == q->front)
	{
		return FAILURE;
	}

	int e;
	Node *p = q->front->next;
	e = p->data;
	q->front->next = p->next;
	if (!p->next)  //只剩下最后一个结点时,再出队,需要修改rear尾指针,在这之前rear都不需要动
	{//特殊考虑
		q->rear = q->front;
	}
	free(p);

	return e;

}

int GetFirst(Q *q)
{
	if(NULL == q || q->front == q->rear)
	{
		return FAILURE;
	}

	return q->front->next->data;
}

int QueueEmpty(Q *q)
{
	if (q == NULL)
	{
		return 1;
	}
	return (q->front == q->rear) ? TRUE : FALSE;
}


int ClearQueue(Q *q) //清空队列
{
	if(NULL == q)
	{
		return FAILURE;
	}

	Node *p = q->front->next;
	while(p)
	{
		q->front->next = p->next;
		free(p);
		p = q->front->next;
	}

	q->rear = q->front;
	return SUCCESS;
}

int QueueDestory(Q **q)
{
	if (q == NULL || (*q) == NULL)
	{
		return FAILURE;
	}

	free((*q)->front);  //释放头结点
	free(*q);
	
	*q = NULL;

	return SUCCESS;
}

队列为空时,front、rear指针指向头结点。不为空时,front指向头结点,rear指向队尾元素。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值