我正在尝试一个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.
更多推荐
发布评论