题目描述
小王子有一天迷上了排队的游戏,桌子上有标号为 1-101−10 的 1010 个玩具,现在小王子将他们排成一列,可小王子还是太小了,他不确定他到底想把那个玩具摆在哪里,直到最后才能排成一条直线,求玩具的编号。已知他排了 MM 次,每次都是选取标号为 XX 个放到最前面,求每次排完后玩具的编号序列。
要求一:采用循环链表解决
输入描述
第一行是一个整数 MM,表示小王子排玩具的次数。
随后 MM 行每行包含一个整数 XX,表示小王子要把编号为 XX 的玩具放在最前面。
输出描述
共 MM 行,第 ii 行输出小王子第 ii 次排完序后玩具的编号序列。
输入输出样例
示例 1
输入
5
3
2
3
4
2
copy
输出
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
copy
运行限制
最大运行时间:1s
最大运行内存: 128M
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
struct Node
{
int data;
Node *before;
Node *next;
};
Node *head=new Node;
void insertt(int x)
{
Node *temp=new Node;
temp->data=x;
temp->next=head->next;
head->next=temp;
temp->before=head;
if(temp->next!=0)
{
temp->next->before=temp;
}
}
void init()
{
for(int i=10; i>=1; i--)
{
insertt(i);
}
}
void deletee(int tap)
{
for(Node *t=head->next;t!=0;t=t->next)
{
if(t->data==tap)
{
t->before->next=t->next;
t->next->before=t->before;
return;
}
}
}
void show()
{
for(Node *t=head->next;t!=0;t=t->next)
{
printf("%d ",t->data);
}
printf("\n");
}
int main()
{
head->next=0;
head->before=0;
init();
int n,x;
scanf("%d",&n);
while(n--)
{
scanf("%d",&x);
deletee(x);
insertt(x);
show();
}
return 0;
}
双向链表的删除操作更好理解一点,就是建立的时候不是太方便,链表结束,nullpt依旧不好用,Null也不能用,继续求抬