题目描述
小王子有一天迷上了排队的游戏,桌子上有标号为 1-101−10 的 1010 个玩具,现在小王子将他们排成一列,可小王子还是太小了,他不确定他到底想把那个玩具摆在哪里,直到最后才能排成一条直线,求玩具的编号。已知他排了 MM 次,每次都是选取标号为 XX 个放到最前面,求每次排完后玩具的编号序列。
要求一:采用单链表解决
输入描述
第一行是一个整数 MM,表示小王子排玩具的次数。
随后 MM 行每行包含一个整数 XX,表示小王子要把编号为 XX 的玩具放在最前面。
输出描述
共 MM 行,第 ii 行输出小王子第 ii 次排完序后玩具的编号序列。
输入输出样例
示例 1
输入
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
运行限制
- 最大运行时间:1s
- 最大运行内存: 128M
题解1(使用暴力破解)
思路:先找到这个元素,然后临时保存一下,记录所在下标(比如说所在位置L),从L开始将之前的元素逐个向后移动,每次都覆盖掉之前的值,最后将元素放到第一个位置即可
以元素5为例
代码如下
#include <iostream>
using namespace std;
int data[11]={0,1,2,3,4,5,6,7,8,9,10};
int find(int x ){
for(int i=1;i<=10;i++)
if(data[i]==x) return i;//找到X返回
}
void moveEle(int L){
//拿走了X,X在L位置,所以将L-1向后移动到L,依次向后移动空处最前面的位置
int temp;
temp =data[L];
for(int i=L;i>=2;i--){ //循环从L位置到2号位置
data[i]=data[i-1]; //向后移动
}
data[1]=temp;
}
int main()
{
int m;
cin >>m;
for(int i=1;i<=m;i++){ //循环M次
int x;
cin>>x;
int l= find(x);
moveEle(l);
for(int j=1;j<=10;j++){
cout<<data[j]<<' '; //输出
}
cout<<endl;
}
return 0;
}
测试不会超时,可以AC
题解2(使用单链表)C++代码实现
#include <iostream>
using namespace std;
struct Node
{
int data;
Node *next;
};
Node *head = new Node; //先生成头结点
void init()
{
head->next = nullptr; //形成空链,由上文已知单链表最后一个结点的指针为空。
for (int i = 10; i >= 1; i--)
{
Node *temp = new Node;
temp->data = i;
temp->next = head->next;
head->next = temp;
}
}
void del(int x)
{
Node *Befor = head; //用于存放当前节点的前驱,因为单链表单向遍历,我们不能从下一个找到上一个
for (Node *T = head->next; T != nullptr; T = T->next) //链表的遍历常用写法
{
if (T->data == x) //找到要的那个数了
{
Node *temp = T; //先临时保存结点
Befor->next = T->next; //将节点从链表上摘除
delete temp; //从内存中删除结点。
return; //删除结束后,结束函数。
}
Befor = T; //前驱改变
}
}
void insert(int x)
{
Node *temp = new Node;
temp->data = x;
temp->next = head->next;
head->next = temp;
}
void show(int i)
{
cout << "这是第" << i << "次操作"; //提交代码时删掉这一行
for (Node *T = head->next; T != nullptr; T = T->next) //链表的遍历常用写法
{
cout << T->data << " ";
}
cout << endl;
}
int main()
{
init();
show(0);//提交代码时删掉这一行
int N;
cin >> N;
for (int i = 1; i <= N; i++)
{
int x;
cin >> x;
del(x);
insert(x);
show(i);
}
}
测试结果
提交代码时候可以删掉测试代码