list.push_back && list.push_front

list.push_back在链表的最后插入

list.push_front在链表的首位插入

#include<iostream>
#include<list>
using namespace std;

int main() {
	list <int> a;
	list <int>::iterator Iter;

	a.push_back(10);
	a.push_back(20);
	a.push_front(30);
	a.push_front(40);
	for (Iter = a.begin(); Iter != a.end(); Iter++) {
		cout << *Iter << endl;
	}
	return 1;
}

结果:

其中:

a.begin()指向容器中最开始数据的位置的指针

a.end()指向容器中最后一个数据的位置+1的指针

这段代码可以进行以下优化: 1. 在 Queue 类中加入一个私有成员变量 max,表示队列中元素的最大值。在 Push() 函数中判断加入的元素是否大于 max,如果大于,则更新 max 的值。这样可以避免每次 Pop() 函数都需要遍历整个队列来找出最大值。 2. 在 Pop() 函数中,先判断队列是否为空,如果为空则直接返回,避免在空队列中 Pop() 引发的错误。 3. 在 main() 函数中,可以通过使用 while 循环来遍历并输出队列中的元素,避免使用 for 循环的不必要计数器。 修改后的代码如下所示: ``` template<class T> class Queue { List<T> queueL; T max; // 添加一个私有成员变量 max public: Queue() : max(0) {} // 在构造函数中初始化 max ~Queue(){} int Size() const { return queueL.Size(); } int Empty() const { return queueL.Empty(); } const T& Front() const { return queueL.Front(); } void Push(const T& item) { queueL.Push_back(item); if (item > max) max = item; // 更新 max 的值 } T Pop() { if (queueL.Empty()) return T(); // 如果队列为空,直接返回 T item = queueL.Front(); queueL.Pop_front(); return item; } void Clear() { queueL.Clear(); } T GetMax() const { return max; } // 添加一个公有成员函数 GetMax(),返回最大值 max }; int main() { Queue<int> q; q.Push(18); q.Push(22); q.Push(88); while (!q.Empty()) cout << q.Pop() << endl; // 使用 while 循环遍历并输出队列中的元素 cout << "max: " << q.GetMax() << endl; // 输出最大值 } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值