C语言中的链表和指针
嗨,伙计们,我正在学习C语言,我很难理解这段代码:C语言中的链表和指针,c,linked-list,C,Linked List,嗨,伙计们,我正在学习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
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 struct变量,该怎么做(这是我的问题):
我确实理解代码,但我不明白如果我们不做head=something,变量head将如何变化
还有,如何可能有两个同名的变量(当前)
谢谢
顺便说一句,我在这里找到了代码:对于结构a->b访问结构a中存储在b中的内容。这意味着行current=current->next实际上表示set current等于struct current中存储在下一个变量中的内容。换句话说,转到列表中的下一项。行
previous->next = current->next;
previous
变量具有链表中上一项的地址。它可以有头的地址
作为任何其他项目
您只需设置下一个项目就是后面的项目。类似于:
如果删除列表中的任何项目(第一个项目除外,
标题和第二个项目除外),则不必更改标题。发布代码的方式不起作用,因为它确实错过了删除标题
指针中的初始节点。但是,您省略了一些显然可以解决问题的代码。以下是原始删除中的代码:
//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;
}
这是代码在删除后调整头指针的地方。这段代码的唯一问题是,它在教程正文中的任何地方都不会调用free
,但不幸的是,这样的错误在免费网站和书中都很常见
下面是一个使用单个双指针执行相同操作的实现:
struct node* delete(int key) {
struct node** ptrCurrent = &head;
while (*ptrCurrent) {
if ((*ptrCurrent)->key == key) {
struct node* tmp = *ptrCurrent;
*ptrCurrent = (*ptrCurrent)->next;
free(tmp);
break;
}
ptrCurrent = &((*ptrCurrent)->next);
}
}
因为您在教程中省略了函数定义,并发布了无意义的内联代码。您确实错过了函数的一部分。请参阅本教程的更多详细信息。您在此处拥有的部分只找到要删除的部分。下面的代码进行删除。很抱歉,我搞砸了,错过了函数的某些部分,你能再次阅读我的问题吗?这不会改变当前->下一步的解释。至于第二部分,我不相信你有两个不同的变量。结构节点*current=NULL;是说取名为current的note类型的结构并将其设为null,而不是重新声明它。似乎是最好的anwser。对不起,先生,节点后面的两个**是什么?@Edw4rd这是指向指针声明的指针。浏览代码以了解其工作原理:它首先指向头部
,然后移动到指向第一个节点的下一个
,然后指向第二个节点的下一个
,依此类推。这样,您就可以将指针指定给头
或下一个
,而不知道要指定哪个指针。
struct node* delete(int key) {
struct node** ptrCurrent = &head;
while (*ptrCurrent) {
if ((*ptrCurrent)->key == key) {
struct node* tmp = *ptrCurrent;
*ptrCurrent = (*ptrCurrent)->next;
free(tmp);
break;
}
ptrCurrent = &((*ptrCurrent)->next);
}
}