写了五六道链表题,终于能完全靠自己写出一份了

我没有按照题目要求来做,没有使用双向循环指针来做,我把需要判断的序号提前了一位,就免去了这个麻烦

下面粘代码:

  1. #include<iostream>
  2. using namespace std;
  3. struct list
  4. {
  5. int value;
  6. list* next;
  7. };
  8. void myshow(list* a);
  9. void myinsert(list* a,int b,int c);
  10. void mydelete(list* a,int b);//按题意来说只用写三个函数
  11. int main()
  12. {
  13. short p;
  14. int i, m;
  15. list* head = (list*)malloc(sizeof(list));
  16. head->next = NULL;
  17. while (cin>>p)
  18. {
  19. if (!p)myshow(head);
  20. if (p == 1) {
  21. cin >> i >> m;
  22. myinsert(head, i-1, m);
  23. //将判断的序号提前一位可以免去双指针的麻烦
  24. }
  25. if (p == 2) {
  26. cin >> i;
  27. mydelete(head, i-1);
  28. //将判断的序号提前一位可以免去双指针的麻烦
  29. }//分三类情况来处理
  30. }
  31. return 0;
  32. }
  33. void myshow(list* a)
  34. {
  35. list* b = a;
  36. while (b->next)
  37. {
  38. b = b->next;
  39. cout << b->value << " ";
  40. }
  41. cout << endl;
  42. }
  43. void myinsert(list* a,int b,int c)
  44. {
  45. list* d = a;
  46. while (b--)
  47. {
  48. d = d->next;
  49. }
  50. list* e = (list*)malloc(sizeof(list));
  51. e->value = c;
  52. e->next = d->next;
  53. d->next = e;
  54. }
  55. void mydelete(list* a, int b)
  56. {
  57. list* c = a;
  58. while(b--)
  59. {
  60. c = c->next;
  61. }
  62. list* d = c->next->next;
  63. list* e = c->next;
  64. c->next = d;
  65. free(e);
  66. }//没用双指针,代码明显变短了

欢迎吐槽,后续我再更新一下双指针的写法

点赞(0)
 

9.9 分

1 人评分

 

C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:

一点编程也不会写的:零基础C语言学练课程

解决困扰你多年的C语言疑难杂症特性的C语言进阶课程

从零到写出一个爬虫的Python编程课程

只会语法写不出代码?手把手带你写100个编程真题的编程百练课程

信息学奥赛或C++选手的 必学C++课程

蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程

手把手讲解近五年真题的蓝桥杯辅导课程

评论列表 共有 0 条评论

暂无评论