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. int data;
  9. LNode* next;
  10. LNode() {};
  11. LNode(int e, LNode* n = NULL) :data(e), next(n) {};
  12. };
  13. //单链表list类创建
  14. class List {
  15. protected:
  16. LNode* head;
  17. int _size;
  18. public:
  19. //构造函数
  20. List() {
  21. head = new LNode;
  22. head->next = NULL;
  23. _size = 0;
  24. }
  25. //析构函数
  26. ~List() {
  27. while (head->next) {
  28. LNode* p = head->next;
  29. head->next = p->next;
  30. delete p;
  31. }
  32. delete head; // 删除头结点
  33. };
  34. //在链表头部插入元素
  35. void insert(int& e) {
  36. _size++;
  37. LNode* p = new LNode(e, head->next);
  38. head->next = p;
  39. }
  40. //在指定位置插入元素
  41. void insert(int index, int a) {
  42. if (index < 1 || index > _size + 1)
  43. return; //无效的插入位置,直接返回
  44. _size++;
  45. LNode* p = head;
  46. //移动p到要插入位置的前一个节点
  47. for (int i = 1; i < index; i++)
  48. p = p->next;
  49. LNode* tmp = new LNode(a);
  50. tmp->next = p->next;
  51. p->next = tmp;
  52. }
  53. //打印链表
  54. void print_L() {
  55. LNode* p = head->next;
  56. while (p != NULL) {
  57. cout << p->data << " ";
  58. p = p->next;
  59. }
  60. cout << endl;
  61. }
  62. //交换两个节点位置
  63. int change() {
  64. int x, y;
  65. cin >> x >> y;
  66. if (x < 0 || x > _size || y < 0 || y > _size) {
  67. cout << "error" << endl;
  68. return -1;
  69. }
  70. if (x == y) // 如果x和y相同,不进行交换操作
  71. return 0;
  72. LNode* px_prev = head; // 节点x的前一个节点指针
  73. for (int i = 1; i < x; i++)
  74. px_prev = px_prev->next;
  75. LNode* py_prev = head; // 节点y的前一个节点指针
  76. for (int i = 1; i < y; i++)
  77. py_prev = py_prev->next;
  78. LNode* px = px_prev->next; // 节点x指针
  79. LNode* py = py_prev->next; // 节点y指针
  80. px_prev->next = py;
  81. py_prev->next = px;
  82. LNode* tmp_next = px->next; // 暂存节点x的下一个节点指针
  83. px->next = py->next;
  84. py->next = tmp_next;
  85. return 0;
  86. }
  87. };
  88. int main() {
  89. List LB;
  90. int n, a;
  91. cin >> n;
  92. for (int i = 0; i < n; i++) {
  93. cin >> a;
  94. LB.insert(i + 1, a);
  95. }
  96. LB.print_L();
  97. int t;
  98. cin >> t;
  99. for (int i = 0; i < t; i++) {
  100. int a = LB.change();
  101. if (a == -1)
  102. continue;
  103. LB.print_L();
  104. }
  105. }

这个修改版将原来的头插法改为了在链表头部插入元素,同时对节点位置交换的逻辑进行了修正。


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?