题目描述

给定N个整数,将这些整数中与M相等的删除
假定给出的整数序列为:1,3,3,0,-3,5,6,8,3,10,22,-1,3,5,11,20,100,3,9,3
应该将其放在一个链表中,链表长度为20
要删除的数是3,删除以后,链表中只剩14个元素:1 0 -3 5 6 8 10 22 -1 5 11 20 100 9
要求:必须使用链表,不允许使用数组,也不允许不删除元素直接输出
程序中必须有链表的相关操作:建立链表,删除元素,输出删除后链表中元素,释放链表
不符合要求的程序即使通过,也会算作0分

样例

  1. 20
  2. 1 3 3 0 -3 5 6 8 3 10 22 -1 3 5 11 20 100 3 9 3
  3. 3

算法

用数组模拟链表, h 表示头结点,t表示尾节点,e[N]表示编号, ne[N]表示后继节点的数组下标,idx表示当前用到的数组下表

(暴力枚举) $O(n^2)$

C++ 代码

  1. #include <iostream>
  2. using namespace std;
  3. const int N = 200010;
  4. int h = -1,t, e[N], ne[N], idx;
  5. int n;
  6. int target;
  7. void add_to_head(int x){
  8. e[idx] = x;
  9. ne[idx] = h;
  10. h = idx ++;
  11. t = h;
  12. }
  13. void add_to_tail(int x){
  14. e[idx] = x;
  15. ne[t] = idx ++;
  16. t = ne[t];
  17. ne[t] = -1;
  18. }
  19. int main(){
  20. cin >> n;
  21. int x;
  22. cin >> x;
  23. add_to_head(x);
  24. n --;
  25. while(n --){
  26. cin >> x;
  27. add_to_tail(x);
  28. }
  29. cin >> target;
  30. while(e[h] == target) h = ne[h];
  31. int cur = h;
  32. while(cur != -1 && ne[cur] != -1){
  33. while(e[ne[cur]] == target) ne[cur] = ne[ne[cur]];
  34. cur = ne[cur];
  35. }
  36. for(int i = h; i != -1; i = ne[i]) cout << e[i] << " ";
  37. return 0;
  38. }