用链表实现队列

QueueByList.h

#ifndef _QUEUE_H

typedef struct Node * PtrNode;
typedef struct QueueByList * PtrQueueByList;

PtrQueueByList CreateQueue();
bool IsEmpty(PtrQueueByList Q);
void EnQueue(PtrQueueByList Q,int X);
int DeQueue(PtrQueueByList Q);
void DeleteQueue(PtrQueueByList Q);

#endif //_QUEUE_H

struct QueueByList
{
	PtrNode frontQ;
	PtrNode rearQ;
};

struct Node
{
	int m_value;
	PtrNode m_next;
};

QueueByList.cpp

#include "StdAfx.h"
#include "QueueByList.h"

PtrQueueByList CreateQueue()
{
	PtrQueueByList Q = NULL;
	Q = new QueueByList();
	Q->frontQ = NULL;
	Q->rearQ = NULL;
	return Q;
}

bool IsEmpty(PtrQueueByList Q)
{
	if (Q->frontQ == NULL && Q->rearQ == NULL)
		return true;
	else
		return false;
}

void EnQueue(PtrQueueByList Q,int X)
{
	PtrNode P = NULL;
	P = new Node();
	P->m_value = X;
	if (IsEmpty(Q))
		Q->frontQ = Q->rearQ = P;
	else
	{
		Q->rearQ->m_next = P;
		Q->rearQ = P;
	}
}

int DeQueue(PtrQueueByList Q)
{
	if (IsEmpty(Q))
		throw "Empty queue!";
	else
	{
		//到了最后一个节点出列时,需要处理rear指针
		//否则该节点出列并删除之后,rear指针悬垂
		//同时也为了保持队列为空的判断条件
		if (Q->frontQ == Q->rearQ)
			Q->rearQ = NULL;

		int X = Q->frontQ->m_value;
		PtrNode P = Q->frontQ->m_next;
		delete Q->frontQ;//别忘了删除节点
		Q->frontQ = P;
		return X;
	}
}

void DeleteQueue(PtrQueueByList Q)
{
	while (!IsEmpty(Q))
		DeQueue(Q);
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值