2017-10-19 73 views
1

嗨,大家好,我学习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从链表元素,但我不知道如何,如果我们没有碰到头结构变量(这是我的麻烦):

//bypass the current link 
    previous->next = current->next; 

我明白的代码,但我不明白的变量头怎么会变化,如果我们不要做头=某事。

而且,它是如何的更多钞票,以具有相同的名称(当前)

感谢

顺便说一句,我发现这里的代码两个变量:https://www.tutorialspoint.com/data_structures_algorithms/linked_list_program_in_c.htm

+1

因为你省略本教程中的函数定义和发布荒谬内嵌代码。 –

+0

你真的错过了功能的一部分。更详细的参见教程。您在这里找到的部分只能找到要删除的部分。代码在下面删除。 – Kajienk

回答

1

代码发布的方式不起作用,因为它确实没有删除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); 
    } 
} 
+0

看起来像que best anwser。不好意思,先生,节点后面的两个**是什么? – Edw4rd

+0

@ Edw4rd这是指针声明的指针。通过代码来看看它是如何工作的:它首先指向head,然后移动到指向第一个节点的next,然后指向第二个节点的next,等等。这可以让你指定一个指向'head'或者'next'的指针而不知道你正在分配哪一个。 – dasblinkenlight

0

对于结构A-> B访问什么存储在结构a中的b中。这意味着线路电流=电流 - >下一个实际上是指设置电流等于存储在结构电流中的下一个变量中的电流。换句话说,转到列表中的下一个项目。

+0

对不起,我搞砸了,错过了功能的一些部分,请你再读一遍我的问题吗? – Edw4rd

+0

这不会改变current-> next的解释。至于第二部分我不相信你有两个不同的变量。 struct node * current = NULL;就是说把注释类型的结构命名为current,并将其设为null,而不是重新声明它。 – Falderol

0

对于线

previous->next = current->next; 

previous变量在链表上一个项目的地址。它可以有任何其他项目的地址head

你只是设置下一个项目是后面的一个。类似于:

如果删除列表中的任何项目(除了第一个 - head和第二个项目),则不必更改head