ZBLOG

使用单链表的其他方法实现该代码:#ifndef NULL #define NULL 0 #endif #include using namespace std; //定义单链表结点结构 struct LNode { int data; LNode* next; LNode() {}; LNode(int e, LNode* n = NULL) :data(e), next(n) {}; }; //单链表list类创建 class List { protect...

下面是使用另一种方法实现的代码:

  1. #ifndef NULL
  2. #define NULL 0
  3. #endif
  4. #include<iostream>
  5. using namespace std;
  6. //定义单链表结点结构
  7. struct LNode
  8. {
  9. int data;
  10. LNode* next;
  11. LNode() {};
  12. LNode(int e, LNode* n = NULL) :data(e), next(n) {};
  13. };
  14. //单链表list类创建
  15. class List
  16. {
  17. protected:
  18. LNode* head;
  19. int _size;
  20. void init() {
  21. head = new LNode;
  22. head->next = NULL;
  23. _size = 0;
  24. }
  25. public:
  26. //构造函数
  27. List(){init();}
  28. //析构函数
  29. ~List() {
  30. LNode* p = head->next;
  31. while (p)
  32. {
  33. LNode* tmp = p->next;
  34. delete p;
  35. p = tmp;
  36. }
  37. delete head; // 删除头节点
  38. head = NULL; // 将头节点指针置为空指针,防止悬空指针的问题
  39. _size = 0; // 链表长度置为0
  40. };
  41. // 头节点不存储信息,所以删除 info() 函数
  42. //修改头插法 insert 函数,使用传入参数 a 的引用进行操作(方便外部代码使用)
  43. void insert(int& a)
  44. {
  45. _size++;
  46. LNode* p = new LNode(a,head->next);
  47. head->next = p;
  48. }
  49. // 修改 print_L 函数,去除头节点的数据输出
  50. void print_L()
  51. {
  52. LNode* p = head->next; // 头节点的下一个节点开始遍历输出
  53. while (p != NULL)
  54. {
  55. cout << p->data << " ";
  56. p = p->next;
  57. }
  58. cout << endl;
  59. }
  60. // 修改 change 函数,使用传入参数 x、y 的引用进行操作(方便外部代码使用)
  61. int change(int& x, int& y)
  62. {
  63. if (x<0 || x>_size || y<0 || y>_size)
  64. {
  65. cout << "error" << endl;
  66. return -1;
  67. }
  68. LNode* p = head->next; // 头节点的下一个节点开始遍历查找第 x 个节点
  69. LNode* s = head->next; // 头节点的下一个节点开始遍历查找第 y 个节点
  70. for (int i = 1; i < x; i++)
  71. {
  72. p = p->next;
  73. }
  74. LNode* tmp1 = p->next;
  75. p->next = tmp1->next;
  76. for (int j = 1; j < y; j++)
  77. {
  78. s = s->next;
  79. }
  80. tmp1->next = s->next;
  81. s->next = tmp1;
  82. return 0;
  83. }
  84. };
  85. int main()
  86. {
  87. List LB;
  88. int n, a;
  89. cin >> n;
  90. for (int i = 0; i < n; i++)
  91. {
  92. cin >> a;
  93. LB.insert(a);
  94. }
  95. LB.print_L();
  96. int t, x, y;
  97. cin >> t;
  98. for (int i = 0; i < t; i++)
  99. {
  100. cin >> x >> y;
  101. if (LB.change(x, y) == -1)
  102. continue;
  103. LB.print_L();
  104. }
  105. }

这里对头插法 insert() 函数和节点的遍历操作进行了修改,使其更符合传入引用参数的使用方式。同时还对 print_L()change() 函数做了相应的修改以适应新的数据结构定义。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=9580

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?