【发布时间】:2020-02-04 17:35:15
【问题描述】:
我有一个简单的函数,可以从单个链表中搜索具有给定键的节点并将其删除。 当具有给定键的节点无处不在时,该函数起作用,除非该节点是列表的头部。 为什么会这样?
#include<stdio.h>
#include<stdlib.h>
struct Node{
int data;
struct Node* next;
};
void printlist(struct Node* node){
while(node!=NULL){
printf("%d", node->data);
node = node->next;
}
printf("\n");
}
/* Given a reference (pointer to pointer) to the head of a list
and a key, deletes the first occurrence of key in linked list */
void deleteNode(struct Node* head, int key){
if(head->data==key){
head = head->next;
}
else {
while(head->next->data!=key){
head = head->next;
}
head->next = head->next->next;
}
}
int main(){
struct Node* first = (struct Node*)malloc(sizeof(struct Node));
struct Node* second = (struct Node*)malloc(sizeof(struct Node));
struct Node* third = (struct Node*)malloc(sizeof(struct Node));
first->data = 1;
second->data = 2;
third->data = 3;
first->next = second;
second->next = third;
third->next = NULL;
printlist(first); // prints 123
deleteNode(first, 2);
printlist(first); // prints 13
deleteNode(first, 1);
printlist(first); // still prints 13
}
【问题讨论】:
-
在第二次调用
deleteNode之后,您认为first指向什么?线索:在第一次致电deleteNode后,您认为它指向什么? -
虽然您的函数的注释是正确的,但原型不对应,您没有发送指向指针的指针;) 尝试在发送
&first时使其工作,而不仅仅是first -
@Angevil - 当您输入您的评论时,我正在输入我的答案。也许我做的太多了?让我们看看OP的感受。
-
@Adrian 我习惯教C,所以我更喜欢提供线索而不是解决方案^=^
-
我也在教学/学习环境中工作。但是,有时,更广泛的“线索”可能会有所帮助:以身作则。
标签: c linked-list reference singly-linked-list