队列的链表实现(c++)

实现功能(FIFO):

1.入队push()

2.出队pop()

3.获取队头front()

4.查询队列的所有元素select()

以下C++代码采用尾插法推入与头删法推出,使得符合先进先出(FIFO)规则:

#include<iostream>

using namespace std;

class MyQueue {
	private:
		struct ListNode {
			int data;
			ListNode* next;
		};
		ListNode* head;
		
	public:
		MyQueue() {
			head = nullptr;
		}
		~MyQueue() {//采用头删法析构
			if (!head) return;
			ListNode* now = head;
			ListNode* next = nullptr;
			while (now->next) {
				next = now->next;
				delete now;
				now = next;
			}
			delete now;
			now = nullptr;
		}
		ListNode* CreateNode(int value) {
			ListNode* newNode = new ListNode;
			newNode->data = value;
			newNode->next = nullptr;

			return newNode;
		}
		//推入数据(尾插)
		void push(int value) {
			ListNode* newNode = CreateNode(value);
			if (!head) {
				head = newNode;
			} else {
				ListNode* temp = head;
				while (temp->next) {
					temp = temp->next;
				}
				temp->next = newNode;
			}
		}
		//推出数据(头删)
		void pop() {
			if (!head) {
				cout << "此队列为空,不可再删!!" << endl;
				return;
			}
			ListNode* now = head;
			ListNode* next = nullptr;
			if (now->next) {
				next = now->next;
				delete now;
				now = next;
				head = next;
			} else {
				delete now;
				now = nullptr;
			}
		}
		//查询队头
		void front() {
			if (!head) {
				cout << "队列为空!!没有队头!!" << endl;
				return;
			}
			cout << "front: " << head->data << endl;
		}
		//查询全部数据
		void select() {
			if (!head) {
				cout << "队列为空!!" << endl;
				return;
			}
			ListNode* temp = head;
			while (temp) {
				cout << temp->data << " ";
				temp = temp->next;
			}
			cout << endl;
		}
};

int main() {
	MyQueue myQueue;
	for (int i = 0; i <= 8; i++) {
		myQueue.push(i);
	}
	for (int i = 0; i <= 1; i++) {
		myQueue.pop();
	}
	myQueue.front();
	myQueue.select();
	return 0;
}

运行效果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_xian_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值