ZBLOG

#include using namespace std; // 单链表节点定义 struct ListNode { int data; ListNode* next; }; // 尾插法创建单链表 ListNode* createList(int n) { ListNode* head = new ListNode(); head->next = nullptr; ListNode* tail = head; f...

你的代码已经正确实现了在单链表中根据位置插入元素,并进行相应的错误处理。以下是对你的代码稍作修改,添加了输出”error”的逻辑:

  1. #include <iostream>
  2. using namespace std;
  3. // 单链表节点定义
  4. struct ListNode {
  5. int data;
  6. ListNode* next;
  7. };
  8. // 尾插法创建单链表
  9. ListNode* createList(int n) {
  10. ListNode* head = new ListNode();
  11. head->next = nullptr;
  12. ListNode* tail = head;
  13. for (int i = 0; i < n; ++i) {
  14. int num;
  15. cin >> num;
  16. ListNode* newNode = new ListNode();
  17. newNode->data = num;
  18. newNode->next = nullptr;
  19. tail->next = newNode; // 新节点添加到链表末尾
  20. tail = newNode; // 更新尾节点
  21. }
  22. return head;
  23. }
  24. // 打印单链表
  25. void printList(ListNode* head) {
  26. if (head == nullptr || head->next == nullptr) {
  27. cout << "empty" << endl;
  28. return;
  29. }
  30. ListNode* cur = head->next;
  31. while (cur != nullptr) {
  32. cout << cur->data << " ";
  33. cur = cur->next;
  34. }
  35. cout << endl;
  36. }
  37. // 获取链表长度
  38. int getListLength(ListNode* head) {
  39. int length = 0;
  40. ListNode* cur = head->next;
  41. while (cur != nullptr) {
  42. length++;
  43. cur = cur->next;
  44. }
  45. return length;
  46. }
  47. // 根据位置插入元素到链表中
  48. void insertNode(ListNode*& head, int position, int targetPosition) {
  49. if (position <= 0 || position > getListLength(head)) { // 检查位置合法性
  50. cout << "error" << endl; // 输出错误提示并返回
  51. return;
  52. }
  53. if (position == targetPosition) { // 若位置相同,链表不会发生改变
  54. printList(head);
  55. return;
  56. }
  57. ListNode* prev = nullptr;
  58. ListNode* cur = head->next;
  59. for (int i = 1; i < position; ++i) {
  60. prev = cur;
  61. cur = cur->next;
  62. }
  63. if (prev != nullptr) {
  64. prev->next = cur->next; // 移除当前节点
  65. ListNode* insertPosPrev = nullptr;
  66. ListNode* insertPosCur = head->next;
  67. for (int i = 1; i < targetPosition; ++i) { // 找到插入位置的前一个节点
  68. insertPosPrev = insertPosCur;
  69. insertPosCur = insertPosCur->next;
  70. }
  71. if (insertPosPrev != nullptr)
  72. insertPosPrev->next = cur;
  73. cur->next = insertPosCur;
  74. if (insertPosCur == head->next)
  75. head->next = cur;
  76. }
  77. printList(head); // 输出移动后的链表
  78. }
  79. int main() {
  80. int n, t;
  81. cin >> n;
  82. ListNode* listHead = createList(n);
  83. printList(listHead);
  84. cin >> t;
  85. for (int i = 0; i < t; ++i) {
  86. int pos, targetPos;
  87. cin >> pos >> targetPos;
  88. insertNode(listHead, pos, targetPos);
  89. }
  90. return 0;
  91. }

这样修改后,当插入位置不合法时,会输出字符串”error”,并不会输出单链表。


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?