|
|
发表于 2023-4-11 21:37:16
|
显示全部楼层
如果链表中的元素是无序的,您可以使用双重循环遍历链表以去除重复元素。
下面是一个修改后的 deleteNode 函数,它可以处理无序链表中的重复元素:
- struct Node *deleteNode(struct Node *head)
- {
- if(head == NULL)
- {
- return head;
- }
-
- struct Node *current = head;
- struct Node *inner_current, *prev;
- while (current != NULL)
- {
- inner_current = current->next;
- prev = current;
- while (inner_current != NULL)
- {
- if (current->value == inner_current->value)
- {
- prev->next = inner_current->next;
- free(inner_current);
- inner_current = prev->next;
- }
- else
- {
- prev = inner_current;
- inner_current = inner_current->next;
- }
- }
- current = current->next;
- }
-
- return head;
- }
复制代码
这个函数使用双重循环遍历链表。外层循环 (current) 从头节点开始,内层循环 (inner_current) 从 current 的下一个节点开始。
在内层循环中,如果找到与 current 节点值相同的 inner_current 节点,就将其从链表中删除并释放内存。外层循环继续处理下一个节点,直到遍历完整个链表。 |
|