题目描述
小王子有一天迷上了排队的游戏,桌子上有标号为 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
实现源码
单链表
public class 小王子单链表 {
static class Node {
int num;
Node n;
Node(int num) {
this.num = num;
}
}
static Node head = new Node(0);
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//在此输入您的代码...
int times = scan.nextInt();
int[] operations = new int[times];
for (int i = 0; i < times; i++) {
operations[i] = scan.nextInt();
}
scan.close();
//init
head.n = null;
Node temp = head;
for (int i = 1; i <= 10; i++) {
temp = (temp.n = new Node(i));
}
temp.n = null;
//operation
for (int i = 0; i < times; i++) {
del(operations[i]);
insert(operations[i]);
show();
}
}
public static void del(int i) {
Node t = head;
while (t.n.num != i) {
t = t.n;
}
t.n = t.n.n;
}
public static void insert(int i) {//这里是加在头结点的后面
Node t = new Node(i);
t.n = head.n;
head.n = t;
}
public static void show() {
Node t = head.n;
while (t.n != null) {
System.out.print(t.num + "\t");
t = t.n;
}
System.out.print(t.num);
System.out.println();
}
}
双链表
public class 小王子双链表 {
static class Node{
int d;
Node b;
Node n;
Node(int d){
this.d = d;
}
}
static Node h = new Node(0);
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int times = scan.nextInt();
int[] operations = new int[times];
for(int i=0;i<times;i++){
operations[i] = scan.nextInt();
}
scan.close();
//建立链表
Node t = h;
for (int i=1;i<=10;i++){
t.n = new Node(i);
t.n.b = t;
t = t.n;
}
t.n = null;
//operations
for(int i=0;i<times;i++){
del(operations[i]);
insert(operations[i]);
show();
}
}
public static void del(int i){
Node t = h;
while(t.n!=null){
if(t.d==i){
t.b.n = t.n;
t.n.b = t.b;
}
t = t.n;
}
}
public static void insert(int i){//插到头结点后
Node t = new Node(i);
t.n = h.n;
t.n.b = t;
h.n = t;
t.b = h;
}
public static void show(){
Node t = h.n;
while(t.n!=null){
System.out.print(t.d + "\t");
t = t.n;
}
System.out.println(t.d);
System.out.println();
}
}