<分区>
大家好,我正在学习 C,但我无法理解这段代码:
struct node {
int data;
int key;
struct node *next;
};
struct node *head = NULL;
struct node *current = NULL;
//delete a link with given key
struct node* delete(int key) {
//start from the first link
struct node* current = head;
struct node* previous = NULL;
//if list is empty
if(head == NULL) {
return NULL;
}
//navigate through list
while(current->key != key) {
//if it is last node
if(current->next == NULL) {
return NULL;
} else {
//store reference to current link
previous = current;
//move to next link
current = current->next;
}
}
//found a match, update the link
if(current == head) {
//change first to point to next link
head = head->next;
} else {
//bypass the current link
previous->next = current->next;
}
return current;
}
代码确实有效,它正在从 C 中的链表中删除元素,但我不明白如果我们不触及 head 结构变量怎么办(这是我的麻烦):
//bypass the current link
previous->next = current->next;
我理解代码,但我不明白如果我们不做 head=something,变量 head 会如何改变。
另外,如何让两个变量具有相同的名称(当前)
谢谢
顺便说一句,我在这里找到了代码:https://www.tutorialspoint.com/data_structures_algorithms/linked_list_program_in_c.htm