【发布时间】:2019-12-05 07:14:54
【问题描述】:
我正在尝试删除具有特定值的节点。我的节点设置方式是这样的:
typedef struct NodeStruct Node;
//struct for each office item
struct NodeStruct {
int id;
struct NodeStruct *next;
};
typedef struct {
/** Pointer to the first node on the list (or NULL ). */
Node *head;
} List;
目前,我的列表如下所示(下面的每个整数都代表来自 : 1 -> 2 -> 3 -> 4 -> 5 -> 7
我想删除 1 和 4,所以生成的链表如下所示: 2 -> 3 -> 5 -> 6 -> 7
我已经写了下面的代码。方法中key代表值,该值的节点应该被删除。
void delete(int key, List *list)
{
//If linked list is empty (base case):
if (list->head == NULL) {
printf("Invalid command\n");
exit(EXIT_BAD_INPUT);
}
//Store head node
Node *temp = list->head;
//If first node needs to be deleted (special case):
if (key == list->head->id) {
list->head = temp->next; //Change head
free(temp); //Free old head
} else {
//Find previous node of the node to be deleted
while (temp->id != key) {
temp = temp->next;
}
//If the position is more than the number of nodes, throw exception:
if (temp == NULL || temp->next == NULL) {
printf("Invalid command\n");
exit(EXIT_BAD_INPUT);
}
//Node temp->next is the node to be deleted
//Store the pointer to the next of node to be deleted
Node *next = temp->next->next;
//Unlink the node from the linked list
free(temp->next);
temp->next = next;
printf("RECORD DELETED: %d\n", key);
}
}
当我运行此代码时,我收到Segmentation Fault: 11。有人可以帮助我删除具有特定值和列表末尾的节点吗?另外,如何检查链表中是否不存在键值?如果这是一个重复的问题,请提前道歉。
【问题讨论】:
-
旁注。
/** Structure for the whole list, including head and tail pointers. */注释错误,没有尾指针。这是一个很好的例子,为什么应该删除重复代码中的内容的 cmets;他们很容易与代码不同步。相反,cmets 将解释为什么代码是这样的。 -
@Schwern 感谢您的关注,我刚刚编辑了帖子以使其更清晰。
-
您能展示一下您是如何初始化节点的吗?如果它正在使用堆栈内存,
free将不起作用。 -
如果它真的是一个单链表,你总是可以just do this。如果不是这样(管理尾指针、前后链表等),它会变得更加复杂。
-
@WhozCraig 这很聪明,持有指向下一个指针的指针。你能在答案中解释一下吗?
标签: c while-loop linked-list nodes infinite-loop