2017-10-19 77 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