Blue Bridge Cup Preparation Questions <Little Prince Singly Linked List>

topic description

One day the little prince was fascinated by the game of queuing. There were 1010 toys marked 1-101−10 on the table. Now the little prince lined them up, but the little prince was still too young. He was not sure what he wanted to put Where is that toy placed, it can only be arranged in a straight line until the end, ask for the number of the toy. It is known that he has arranged MM times, and each time he selects the numbered XX ones and puts them at the front, and finds the number sequence of the toys after each arrangement.

Requirement 1: Use a single linked list to solve

enter description

The first line is an integer M, indicating the number of times the little prince arranges toys.

Each of the subsequent M lines contains an integer X, indicating that the little prince wants to put the toy numbered X at the front.

output description

There are a total of M lines, and the i-th line outputs the number sequence of the little prince's toy after the ii-th sorting.

Input and output samples

Example 1

enter

5
3
2
3
4
2

output

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

 A very basic question, written in c can exercise the underlying operations of the linked list: create, insert, delete, etc.

Here I write it directly in c++, using the container list, which is very convenient

The key point is to remember some spelling and when pushing, remember that if l1.push forgets to write the previous l1 when writing, it will cause an error

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

void listinit()
{
    for(int i=1;i<=10;i++)
    {
          l1.push_back(i);
    }
}

void show( list<int> &l1)
{
      for(list<int>::iterator it=l1.begin();it !=l1.end();it++)
    {
        cout<<(*it)<<" ";
    }
  cout<<endl;

}

int main()
{
  listinit();
  int M=0;
  int X=0;
  cin >> M;
  for(int j=1;j<=M;j++)
  {
    cin >> X;         //先找到这个编号,然后删了,使用earse
    for(list<int>::iterator it=l1.begin();it != l1.end() ; it++)
    {
      if(*it==X){
        l1.erase(it);
        break;
      }
    }
    l1.push_front(X);   //删了后头插,顺便打印输出
    show(l1);
  }
  // 请在此输入您的代码
  return 0;
}

Guess you like

Origin blog.csdn.net/mc10141222/article/details/123674677