lanqiaoOJ 1110:小王子单链表 ← STL list
【题目来源】
https://www.lanqiao.cn/problems/1110/learning/
【题目描述】
小王子有一天迷上了排队的游戏,桌子上有标号为 1-10 的 10 个玩具,现在小王子将他们排成一列,可小王子还是太小了,他不确定他到底想把哪个玩具摆在哪里,直到最后才能排成一条直线,求玩具的编号。已知他排了 M 次,每次都是选取标号为 X 的放到最前面,求每次排完后玩具的编号序列。
要求一:采用单链表解决
【输入格式】
第一行是一个整数 M,表示小王子排玩具的次数。
随后 M 行每行包含一个整数 X,表示小王子要把编号为 X 的玩具放在最前面。
【输出格式】
共 M 行,第 i 行输出小王子第 i 次排完序后玩具的编号序列。
【输入样例】
5
3
2
3
4
2
【输出样例】
3 1 2 4 5 6 7 8 9 10
2 3 1 4 5 6 7 8 9 10
3 2 1 4 5 6 7 8 9 10
4 3 2 1 5 6 7 8 9 10
2 4 3 1 5 6 7 8 9 10
【算法分析】
★ 在大多数情况下,可以直接使用 C++ 中的 STL list,而不需手写链表。通过这种方式完成的代码通常更简洁。
★ STL list:https://cplusplus.com/reference/list/
(1)size():Returns the number of elements in the list container.
(2)empty():Returns whether the list container is empty (i.e. whether its size is 0).
(3)push_front():Inserts a new element at the beginning of the list, right before its current first element.
(4)push_back():Adds a new element at the end of the list container, after its current last element.
(5)pop_front():Removes the first element in the list container, effectively reducing its size by one.
(6)pop_back():Removes the last element in the list container, effectively reducing the container size by one.
(7)front():Returns a reference to the first element in the list container.
(8)back():Returns a reference to the last element in the list container.
(9)reverse():Reverses the order of the elements in the list container.
(10)insert():The container is extended by inserting new elements before the element at the specified position.
(11)erase():Removes from the list container either a single element (position) or a range of elements ([first,last)).
(12)unique():Notice that an element is only removed from the list container if it compares equal to the element immediately preceding it. Thus, this function is especially useful for sorted lists.
【算法代码】
#include <bits/stdc++.h>
using namespace std;list<int> ls;
void init() {for(int i=1; i<=10; i++) {ls.push_back(i);}
}int main() {init();int m;cin>>m;while(m--) {int x;cin>>x;ls.remove(x);ls.push_front(x);for(auto i:ls) cout<<i<<" ";cout<<endl;}return 0;
}/*
in:
5
3
2
3
4
2out:
3 1 2 4 5 6 7 8 9 10
2 3 1 4 5 6 7 8 9 10
3 2 1 4 5 6 7 8 9 10
4 3 2 1 5 6 7 8 9 10
2 4 3 1 5 6 7 8 9 10
*/
【参考文献】
https://blog.csdn.net/mc10141222/article/details/123674677
https://cplusplus.com/reference/list/list/