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(NULL) {}
  7. };
  8. void insert(ListNode*& head, int val) {
  9. ListNode* newNode = new ListNode(val);
  10. newNode->next = head->next;
  11. head->next = newNode;
  12. }
  13. void printList(ListNode* head) {
  14. ListNode* curr = head->next;
  15. while (curr != NULL) {
  16. cout << curr->val << " ";
  17. curr = curr->next;
  18. }
  19. cout << endl;
  20. }
  21. ListNode* moveElements(ListNode*& head, int srcPos, int destPos) {
  22. if (srcPos == destPos) {
  23. return head;
  24. }
  25. // Find the source node and its previous node
  26. ListNode* prevSrc = head;
  27. for (int i = 0; i < srcPos-1; i++) {
  28. prevSrc = prevSrc->next;
  29. if (prevSrc == NULL || prevSrc->next == NULL) {
  30. return NULL; // Invalid source position
  31. }
  32. }
  33. // Find the destination node and its previous node
  34. ListNode* prevDest = head;
  35. for (int i = 0; i < destPos-1; i++) {
  36. prevDest = prevDest->next;
  37. if (prevDest == NULL || prevDest->next == NULL) {
  38. return NULL; // Invalid destination position
  39. }
  40. }
  41. // Remove the source node from its current position
  42. ListNode* srcNode = prevSrc->next;
  43. prevSrc->next = srcNode->next;
  44. // Insert the source node at the destination position
  45. srcNode->next = prevDest->next;
  46. prevDest->next = srcNode;
  47. return head;
  48. }
  49. int main() {
  50. int n;
  51. cin >> n;
  52. ListNode* head = new ListNode(-1);
  53. for (int i = 0; i < n; i++) {
  54. int val;
  55. cin >> val;
  56. insert(head, val);
  57. }
  58. printList(head); // Output original list
  59. int t;
  60. cin >> t;
  61. for (int i = 0; i < t; i++) {
  62. int srcPos, destPos;
  63. cin >> srcPos >> destPos;
  64. ListNode* result = moveElements(head, srcPos, destPos);
  65. if (result == NULL) {
  66. cout << "error" << endl;
  67. } else {
  68. printList(result); // Output modified list
  69. }
  70. }
  71. return 0;
  72. }

希望对你有所帮助!


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?