ZBLOG

使用单链表来实现改变项目的顺序,要求使用头插法 先用C++实现含头结点的单链表,然后实现单链表中元素的插入。 注意不能改变每个结点包含的数据,必须通过修改指针来实现位置调换。 Input 第一行输入整数 n,表示链表中有n个数据; 第二行依次输入 n个数据,中间用空格分隔; 第三行输入整数t,表示插入的次数; 之后t行,每行两个数,分别为当前的位置和需要插到的位置。注意,位置编号从1开始。 Output 第一行,输出原始列表; 之后t行,输出每一次移动后的结果。 若当前位置和目标位置相同...

以下是用C++实现含头结点的单链表,并根据输入要求进行插入操作的示例代码:

  1. #include <iostream>
  2. using namespace std;
  3. struct ListNode {
  4. int val;
  5. ListNode* next;
  6. ListNode(int x) : val(x), next(nullptr) {}
  7. };
  8. ListNode* createLinkedList(int n) {
  9. ListNode* head = new ListNode(0); // 头结点
  10. ListNode* curr = head;
  11. for (int i = 0; i < n; ++i) {
  12. int num;
  13. cin >> num;
  14. ListNode* newNode = new ListNode(num);
  15. curr->next = newNode;
  16. curr = newNode;
  17. }
  18. return head;
  19. }
  20. void printLinkedList(ListNode* head) {
  21. if (!head)
  22. return;
  23. ListNode* curr = head->next; // 跳过头结点
  24. while (curr) {
  25. cout << curr->val << " ";
  26. curr = curr->next;
  27. }
  28. cout << endl;
  29. }
  30. bool isValidPosition(ListNode* head, int pos) {
  31. int count = 0; // 计数器
  32. ListNode* curr = head->next; // 跳过头结点
  33. while (curr) {
  34. ++count;
  35. if (count == pos)
  36. return true;
  37. curr = curr->next;
  38. }
  39. return false;
  40. }
  41. void insertNode(ListNode* head, int fromPos, int toPos) {
  42. if (!isValidPosition(head, fromPos) || !isValidPosition(head, toPos)) {
  43. cout << "error" << endl;
  44. return;
  45. }
  46. if (fromPos == toPos)
  47. return;
  48. // 找到要移动的节点和其前驱节点
  49. ListNode* fromPrev = head;
  50. for (int i = 0; i < fromPos - 1; ++i)
  51. fromPrev = fromPrev->next;
  52. ListNode* fromNode = fromPrev->next;
  53. ListNode* toPrev = head;
  54. for (int i = 0; i < toPos - 1; ++i)
  55. toPrev = toPrev->next;
  56. // 断开fromNode
  57. fromPrev->next = fromNode->next;
  58. // 将fromNode插入到toPos的前面
  59. ListNode* nextNode = toPrev->next;
  60. toPrev->next = fromNode;
  61. fromNode->next = nextNode;
  62. }
  63. int main() {
  64. int n;
  65. cin >> n;
  66. ListNode* head = createLinkedList(n);
  67. cout << "Original list: ";
  68. printLinkedList(head);
  69. int t;
  70. cin >> t;
  71. while (t--) {
  72. int pos1, pos2;
  73. cin >> pos1 >> pos2;
  74. insertNode(head, pos1, pos2);
  75. cout << "Modified list: ";
  76. printLinkedList(head);
  77. }
  78. return 0;
  79. }

注意:以上代码是基于题目要求实现的简单示例,可能并不完整或最优。在实际情况下,应该考虑更多边界条件和错误处理。


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?