typedef struct _node *Node;
typedef struct _list *List;
typedef struct _list {
Node head;
} list;
typedef struct _node {
int value;
Node next;
} node;
int listDeleteLargest(List l) {
Node meme = l->head;
int largest = meme->value;
while (meme != NULL) {
if (largest < meme->value) {
largest = meme->value;
}
meme = meme->next;
}
Node prev = l->head;
Node temp = prev->next;
Node current = prev->next;
while (current != NULL) {
if (prev->value == largest) {
temp = prev;
prev = prev->next;
l->head = prev;
free(temp);
} else if (current->value == largest) {
if (current->next == NULL) {
prev->next = NULL;
temp = current;
free(temp);
} else {
prev->next = current->next;
current = current->next;
temp = current;
free(temp);
}
}
current = current->next; //runtime error here
}
return 0;
}
//the struct typedef here.
对于这段代码,我试图删除最大的代码。逻辑似乎是正确的,但我在current = current-&gt; next;
期间一直遇到运行时错误例如,如果链表中有两个大数字,它将同时删除两个。我在帐户上编写了代码,如果节点位于结尾,结束和其余部分,它就会满足。我已经运行了测试,但我仍然无法理解为什么它不能正确编译。
答案 0 :(得分:0)
如果current->value != largest
,您最终会执行current = current->next
两次,并冒险离开列表的末尾。
此外,此代码:
temp = current;
free(temp);
将删除current
,因为temp
和current
都指向相同的内容。