从排序的链接列表中删除重复的元素(Remove duplicate elements from a sorted linked list)

编程入门 行业动态 更新时间:2024-10-28 07:20:11
从排序的链接列表中删除重复的元素(Remove duplicate elements from a sorted linked list)

我正在尝试一个C程序来从排序链接列表中删除重复项,我正在使用一个简单的概念遍历从开始节点列表。 遍历时,将每个节点与下一个节点进行比较。 如果下一个节点的数据与当前节点相同,那么我删除下一个节点。

我的代码是:

struct node *remove_dup(struct node *start) { struct node *p,*tmp; p=start; while(p!=NULL) { if(p->info==p->link->info) { tmp=p->link; p->link=p->link->link; free(tmp); } p=p->link; } return start; }

这不是给我正确的答案! 我的执行有什么问题? 我的观念错了吗?

I am attempting a C program to remove duplicates from a Sorted linked list and i am using a simple concept of traversing the list from the start node. While traversing, compare each node with its next node. If data of next node is same as current node then i delete the next node.

My Code is:

struct node *remove_dup(struct node *start) { struct node *p,*tmp; p=start; while(p!=NULL) { if(p->info==p->link->info) { tmp=p->link; p->link=p->link->link; free(tmp); } p=p->link; } return start; }

It is not giving me the correct answer! What is wrong with my execution? Is my concept wrong?

最满意答案

由于你的代码检查了下一个元素,所以当你处于最后一个元素时,你需要停下来,如下所示:

while (p != NULL && p->link != NULL) { ... }

获得条件第一部分的唯一原因是要捕获空列表。

另外,当你移除一个元素时,你不应该使指针前进。 否则,您将不会正确处理超过两个元素的运行。

Since your code examines the next element, you need to stop when you are at the element one before last, like this:

while (p != NULL && p->link != NULL) { ... }

The only reason to have the first part of the condition is to trap empty lists.

In addition, you should not advance the pointer when you remove an element. Otherwise, you would not process runs of more than two elements correctly.

更多推荐

本文发布于:2023-07-15 18:50:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1117469.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   链接   列表中   Remove   duplicate

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!