c - C 中的链表和指针

标签 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 = 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

最佳答案

代码发布的方式不起作用,因为它确实错过了 head 指针中初始节点的删除。但是,您省略了一些显然可以解决问题的代码。以下是原始 delete 中的代码:

//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);
    }
}

关于c - C 中的链表和指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46836579/

相关文章:

c - 当 fscanf 从文本文件读取特定值时结束循环

c - 变量名中间的宏参数?

c - 在c中分配大型指针数组(9mb)

c - 如何从一系列开罗 Canvas 中轻松地用 c 语言创建视频?

c - 从C中的链表中删除多个 'key'节点

删除注释的C程序

c - 将新节点链接到 c 中的链接列表的问题

java - 使用链接列表的学生数据库

java - 向链表添加一个值而不是特定值 - JAVA

c++ - 将两个链表中的特定值相加时出现问题