鱼C论坛

 找回密码
 立即注册
查看: 3643|回复: 4

[已解决]爱学习的我又来啦!麻烦大佬帮忙看看!谢谢

[复制链接]
发表于 2023-4-11 20:56:41 | 显示全部楼层    本楼为最佳答案   
您目前的理解是正确的。在deleteNode函数中,x和head指向同一个链表。

x在函数中用于遍历和更新链表,当遍历完成时,x指向链表的尾节点。所以在函数中返回x时,实际上返回的是链表尾节点的指针地址。

而head始终指向链表的头节点,所以正确的返回值应该是head。

为了修复deleteNode函数,您应该在函数最后返回head,而不是x:

  1. struct Node *deleteNode(struct Node *head)
  2. {
  3.     if(head == NULL)
  4.     {
  5.         return head;
  6.     }
  7.    
  8.     struct Node *x = head;

  9.     while(x->next != NULL)
  10.     {
  11.         if(x->value == x->next->value)
  12.         {
  13.             x->next = x->next->next;
  14.         }
  15.         else
  16.         {
  17.             x = x->next;
  18.         }
  19.     }
  20.    
  21.     return head;
  22. }
复制代码


这样修改后,您的程序将能够正确地去除链表中的重复元素并输出结果。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-4-11 21:37:16 | 显示全部楼层
a905448839 发表于 2023-4-11 21:32
那如果这个题不是开始让我以顺序录入链表,如果是随机的链表值 如
1 2 1 2 5 8 5 8 1 2 3 这样不是相邻 ...

如果链表中的元素是无序的,您可以使用双重循环遍历链表以去除重复元素。

下面是一个修改后的 deleteNode 函数,它可以处理无序链表中的重复元素:

  1. struct Node *deleteNode(struct Node *head)
  2. {
  3.     if(head == NULL)
  4.     {
  5.         return head;
  6.     }
  7.    
  8.     struct Node *current = head;
  9.     struct Node *inner_current, *prev;

  10.     while (current != NULL)
  11.     {
  12.         inner_current = current->next;
  13.         prev = current;
  14.         while (inner_current != NULL)
  15.         {
  16.             if (current->value == inner_current->value)
  17.             {
  18.                 prev->next = inner_current->next;
  19.                 free(inner_current);
  20.                 inner_current = prev->next;
  21.             }
  22.             else
  23.             {
  24.                 prev = inner_current;
  25.                 inner_current = inner_current->next;
  26.             }
  27.         }
  28.         current = current->next;
  29.     }
  30.    
  31.     return head;
  32. }
复制代码


这个函数使用双重循环遍历链表。外层循环 (current) 从头节点开始,内层循环 (inner_current) 从 current 的下一个节点开始。

在内层循环中,如果找到与 current 节点值相同的 inner_current 节点,就将其从链表中删除并释放内存。外层循环继续处理下一个节点,直到遍历完整个链表。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-4-1 23:08

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表