void del_duplicated(struct node *first) {
struct node *current = listfirst, *prev = listfirst, *tmp;
if (current == NULL)
printf("Nothing to delete !\n");
while (current != NULL) {
/* Keeping traverse the list to find the duplicated elements. */
prev = current;
current = current->next;
/* for the first and second duplicated node such as 1 1 2 3 5 */
if (prev->data == listfirst->data && current->data == listfirst->data) {
listfirst = current->next;
printf("LIST FIRST NOW AT %d", listfirst->data);
}
/* The rest requirement such as 1 2 4 4 5 convert to 1 2 5 */
else if ((prev->next)->data == (current->next)->data) {
(prev->next) = (current->next)->next; /*this is point 2 to 5*/
tmp = current; /*delete the node*/
free(tmp);
tmp = current->next;
free(tmp);
}
}
}
我有一个链表问题,需要我从列表中删除“2个重复节点”。 这就像1 1 2 3 5
转换为2 3 5
。 和1 2 4 4 5
将被转换为1 2 5
。从排序的链接列表中一次删除“2个重复”元素
但我的程序崩溃,因为指针指向一个陌生的地方,我不知道为什么。 (.exe已停止工作) 我认为我的移动指针的逻辑确定,但是.... error like this 我的逻辑附加在我的源代码的注释中。
我是一名在台湾学习计算机科学的新手。 请原谅我的坏英语。
编辑 1小时后。
我在我的两位法官声明中添加了BREAK,并且运行良好。 但我不知道为什么。所有的
void del_duplicated(struct node *first) {
struct node *current = listfirst, *prev = listfirst, *tmp, *tmp2;
if (current == NULL)
printf("Nothing to delete !\n");
while (current != NULL) {
/* Keeping traverse the list to find the duplicated elements. */
prev = current;
current = current->next;
//printf("prev %d,current %d\n", prev->data, current->data);
//system("pause");
/* for the first and second duplicated node such as 1 1 2 3 5 */
if (prev->data == listfirst->data && current->data == listfirst->data) {
listfirst = current->next;
system("pause");
break;
}
/* The rest requirement such as 1 2 4 4 5 convert to 1 2 5 */
else if (current->data == (current->next)->data) {
(prev->next) = (current->next)->next; /* this is point 2 to 5 */
tmp = current->next;
tmp2 = current; /* delete the node */
current = (current->next)->next;
free(tmp);
free(tmp2);
break;
}
}
}
你的英语非常好。你应该花一些时间**学习调试**。它将为您节省无数个小时的“为什么这不起作用” – bolov
如果您的列表没有虚拟的第一个节点(这意味着您的第一个节点在第一个示例中保持值为1),那么您正在更改列表地址当你删除你的第一个节点。您必须将列表的地址传递给您的函数才能执行此操作。例如'void del_duplicated(struct node ** first)'。否则,当你删除第一个节点时,你在main()中没有引用你的列表。 –
非常感谢:D我会!!!我刚刚学习C 4个月前〜 – Alfons