1. 程式人生 > 實用技巧 >解決MySQL 8.0 設定簡單密碼報錯ERROR 1819 (HY000): Your password does not satisfy the current policy require...

解決MySQL 8.0 設定簡單密碼報錯ERROR 1819 (HY000): Your password does not satisfy the current policy require...

實現一個單鏈表,連結串列初始為空,支援三種操作:

(1) 向連結串列頭插入一個數;

(2) 刪除第k個插入的數後面的數;

(3) 在第k個插入的數後插入一個數

現在要對該連結串列進行M次操作,進行完所有操作後,從頭到尾輸出整個連結串列。

注意:題目中第k個插入的數並不是指當前連結串列的第k個數。例如操作過程中一共插入了n個數,則按照插入的時間順序,這n個數依次為:第1個插入的數,第2個插入的數,…第n個插入的數。

輸入格式

第一行包含整數M,表示操作次數。

接下來M行,每行包含一個操作命令,操作命令可能為以下幾種:

(1) “H x”,表示向連結串列頭插入一個數x。

(2) “D k”,表示刪除第k個輸入的數後面的數(當k為0時,表示刪除頭結點)。

(3) “I k x”,表示在第k個輸入的數後面插入一個數x(此操作中k均大於0)。

輸出格式

共一行,將整個連結串列從頭到尾輸出。

資料範圍

1M1000001≤M≤100000
所有操作保證合法。

輸入樣例:

10
H 9
I 1 1
D 1
D 0
H 6
I 3 6
I 4 5
I 4 5
I 3 4
D 6

輸出樣例:

6 4 6 5

定義:

head為頭指標

e[N]存放結點的val

ne[N]存放結點的next指標
idex表示第n個插入的結點

初始化:head為-1,idex為0

1 void init()
2 {
3     head = -1;
4     idx = 0;
5 }

向連結串列頭插入一個數:

1 void add_to_head(int x)
2 {
3     e[idx] = x; //接受結點的val
4     ne[idx] = head;
5     head = idx;
6     idx++;
7 }

第k個插入的數後插入一個數

1 void add(int k, int x)
2 {
3     e[idx] = x;
4     ne[idx] = ne[k];
5     ne[k] = idx;
6     idx++;
7 }

刪除:

(1)刪除第一個結點:head = ne[head]

(2)刪除任意一個結點:

1 void remove(int k)
2 {
3     ne[k] = ne[ne[k]];
4 }

還要注意,這裡因為我們的下標從0開始,所以我們第k的結點下標實際上是k-1。

總程式碼

 1 #include <iostream>
 2 using namespace std;
 3 
 4 const int N = 100010;
 5 int head, e[N], ne[N], idx;
 6 
 7 void init()
 8 {
 9     head = -1;
10     idx = 0;
11 }
12 
13 void add_to_head(int x)
14 {
15     e[idx] = x;
16     ne[idx] = head;
17     head = idx;
18     idx++;
19 }
20 
21 void add(int k, int x)
22 {
23     e[idx] = x;
24     ne[idx] = ne[k];
25     ne[k] = idx;
26     idx++;
27 }
28 
29 void remove(int k)
30 {
31     ne[k] = ne[ne[k]];
32 }
33 
34 int main()
35 {
36     int m;
37 
38     cin >> m;
39 
40     init();
41 
42     while(m--)
43     {
44         int k, x;
45         char op;
46 
47         cin >> op;
48         if(op == 'H')
49         {
50             cin >> x;
51             add_to_head(x);
52         }
53         else if(op == 'D')
54         {
55             cin >> k;
56             if(!k) head = ne[head]; //如果刪除的師第一個結點
57             else remove(k-1);
58         }
59         else
60         {
61             cin >> k >> x;
62             add(k-1, x);
63         }
64     }
65 
66     for(int i = head; i != -1; i = ne[i]) cout << i << " ";
67     cout << endl;
68     system("pause");
69     return 0;
70 }