队列另一种实现(链表)

本文介绍了一种基于链表实现的队列数据结构,并详细解释了队列的基本操作,包括入队(push)、出队(pop)和获取队首元素(getFront)等。此外,还提供了完整的C++代码实现,展示了如何在实际应用中使用该队列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

头文件

typedef struct Node
{
	int val;
	Node *next;
	Node(){next=NULL;}
	Node(int v)
	{
		val = v;
		next = NULL;
	}
}Node;

class QueueList
{
public:
	QueueList(int max);
	~QueueList();
	int pop();
	void push(int x);
	int getFront() const;
	int count();

private:
	int m_count;
	int m_max;
	Node* m_head;
	Node* m_tail;
};


cpp

#include "Queue_list.h"

int QueueList::getFront()const
{
	if(m_count<=0)
	{
		throw "QueueList is empty";
		return -1;
	}
	else
	{
		return m_head->val;
	}
}

int QueueList::pop()
{
	if(m_count<=0)
	{
		throw "QueueList is empty";
		return -1;
	}
	else
	{
		m_count--;
		int tmp = m_head->val;
		Node *node = m_head;
		m_head = m_head->next;
        delete node;
        if(m_head==NULL)
        {
            m_tail = NULL;
        }
		return tmp;
	}
}

void QueueList::push(int x)
{
	if(m_count>=m_max)
	{
		throw "QueueList is full";
	}
	else
	{
		Node * node = new Node(x);
		if(m_head == NULL)
		{
			m_head = node;
			m_tail = node;
		}
		else
		{
			m_tail->next = node;
			m_tail = node;
		}
		m_count++;
	}
}

QueueList::QueueList(int max):m_count(0),m_head(0),m_tail(0),m_max(max)
{

}

QueueList::~QueueList()
{
	Node *node;
	while(m_head != NULL)
	{
		node = m_head->next;
		delete m_head;
		m_head = node;
	}
}

int QueueList::count()
{
	return m_count;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值