ZBLOG

修改此代码:在发现某次移动时,输入的位置不合法,直接输出"error"并且该次不打印移动后的结果,直接跳过 #include using namespace std; // 定义链表节点结构体 struct ListNode { int data; ListNode* next; }; // 创建链表 ListNode* createList(int n) { ListNode* head = new ListNode(); Lis...

以下是修改后的代码:

  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. ListNode* cur = head;
  12. for (int i = 0; i < n; i++) {
  13. int num;
  14. cin >> num;
  15. ListNode* newNode = new ListNode();
  16. newNode->data = num;
  17. newNode->next = nullptr;
  18. cur->next = newNode;
  19. cur = cur->next;
  20. }
  21. return head;
  22. }
  23. // 打印链表
  24. void printList(ListNode* head) {
  25. if (head == nullptr || head->next == nullptr) {
  26. return;
  27. }
  28. ListNode* cur = head->next;
  29. while (cur != nullptr) {
  30. cout << cur->data << " ";
  31. cur = cur->next;
  32. }
  33. cout << endl;
  34. }
  35. // 移动元素位置
  36. void moveElement(ListNode* head, int currentPos, int targetPos) {
  37. if (currentPos == targetPos || head == nullptr || head->next == nullptr) {
  38. return;
  39. }
  40. // 获取待移动的节点和其前一个节点
  41. ListNode* prevNode1 = nullptr; // 待移动节点的前一个节点
  42. ListNode* currentNode1 = head; // 待移动节点
  43. while (currentNode1 != nullptr && currentPos > 0) {
  44. prevNode1 = currentNode1;
  45. currentNode1 = currentNode1->next;
  46. currentPos--;
  47. }
  48. if (currentNode1 == nullptr) {
  49. cout << "error" << endl;
  50. return; // 出现错误,直接返回
  51. }
  52. ListNode* prevNode2 = nullptr; // 目标位置节点的前一个节点
  53. ListNode* currentNode2 = head; // 目标位置节点
  54. while (currentNode2 != nullptr && targetPos > 0) {
  55. prevNode2 = currentNode2;
  56. currentNode2 = currentNode2->next;
  57. targetPos--;
  58. }
  59. if (currentNode2 == nullptr) {
  60. cout << "error" << endl;
  61. return; // 出现错误,直接返回
  62. }
  63. // 移动节点
  64. if (prevNode1 != nullptr) {
  65. prevNode1->next = currentNode1->next;
  66. }
  67. if (prevNode2 != nullptr) {
  68. prevNode1->next = currentNode1->next;
  69. currentNode1->next = currentNode2->next;
  70. prevNode2->next = currentNode1;
  71. }
  72. else {
  73. head->next = currentNode1;
  74. currentNode1->next = currentNode2;
  75. }
  76. }
  77. int main() {
  78. int n, t;
  79. cin >> n;
  80. ListNode* head = createList(n);
  81. printList(head);
  82. cin >> t;
  83. for (int i = 0; i < t; i++) {
  84. int currentPos, targetPos;
  85. cin >> currentPos >> targetPos;
  86. moveElement(head, currentPos, targetPos);
  87. printList(head);
  88. }
  89. return 0;
  90. }

修改后的代码会在发现移动位置不合法时输出”error”,并且跳过打印移动后的结果。


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?