2015-12-06 28 views
-1

你好,我有一些麻煩的時候纔來「獲得」一個節點,到目前爲止我的代碼看起來像這樣...如何獲得在C節點沒有搗毀老鏈表

LinklistNode* get_node(LinklistNode* list_head, int index){ 
LinklistNode* temp = list_head; 
if(temp != NULL && index > 0){ 
    LinklistNode* list_pointer = temp; 
    LinklistNode* next_list_pointer = list_pointer ->next; 
    while(next_list_pointer->next != NULL && index >0){ 
     index--; 
     if(index == 0) break; 
     list_pointer = next_list_pointer; 
     next_list_pointer = next_list_pointer ->next; 
    } 
    temp = list_pointer->next; 
    temp->next = NULL; 


} 
else if(index == 0){ 
    return temp; 
} 
return temp; 
} 

...現在我試圖通過它是一個臨時變量,是完全相同的,但我不認爲這是行得通,因爲他們只會分享相同的內存地址,我打電話它如下(也許這將有助於)

LinklistNode* list_head2 = list_head; 
list_head2 = get_node(list_head2,2); 
print_list(list_head2); 
print_list(list_head); 

而從這看起來像這樣的輸出

列表:前任何

LIST_HEAD調用方法list_head2後8 100 7 6 5 3 200 2 1 0 0 1 2 3 4 5 6 7 8

:列表:7

LIST_HEAD在調用後方法:列表:8 100 7

所以我的問題是,我搗毀list_heads值,我不知道如何去做,所以list_heads值和長度不會改變。 任何幫助都將不勝感激。

+0

你可以使用人類語言,它會清楚你想要做什麼? –

+0

LinklistNode * get_node(LinklistNode * list_head,int index)應返回指向列表中索引處的節點的指針,但不會將其刪除。 @VladfromMoscow讓我知道如果清除任何東西 – rickless

回答

1

如果我理解正確的,你需要以下

LinklistNode * get_node(LinklistNode *list_head, unsigned int index) 
{ 
    while (index != 0 && list_head) 
    { 
     --index; 
     list_head = list_head->next; 
    } 

    return list_head; 
} 

原始列表不會改變。

如果你需要提取的節點,則函數可以看看下面的方式

LinklistNode * get_node(LinklistNode **list_head, unsigned int index) 
{ 
    LinklistNode *prev = NULL, *current = *list_head; 

    while (index != 0 && current) 
    { 
     --index; 
     prev = current; 
     current = current->next; 
    } 

    if (prev == NULL) 
    { 
     if (current) *list_head = current->next; 
    } 
    else if (current) 
    { 
     prev->next = current->next; 
    } 

    if (current) current->next = NULL;   

    return current; 
} 

如果你需要一個節點的副本,則函數可以像

LinklistNode * get_node(LinklistNode *list_head, unsigned int index) 
{ 
    LinklistNode *tmp = NULL; 

    while (index != 0 && list_head) 
    { 
     --index; 
     list_head = list_head->next; 
    } 

    if (list_head) 
    { 
     tmp = malloc(sizeof(LinklistNode)); 
     if (tmp) 
     { 
      *tmp = *list_head; 
      tmp->next = NULL; 
     } 
    } 

    return tmp; 
} 
+0

問題是你只想要1節點,如果你這樣做,你從索引到列表的末尾@vladfrommoscow – rickless

+0

@rickless查看我更新的帖子。 –

0

當您刪除該行

temp->next = NULL; 

然後代碼可以正常工作。

+0

然後我得到結果列表:7 6 5 3 200 2 1 0 0 1 2 3 4 5 6 7 8 而輸出應該只是節點的值7 – rickless

+0

然後你必須指定你想要的。什麼是所需的回報價值?它可以是包含指向下一個值的指針的列表節點,也可以是節點的值,函數應返回類似'temp-> data'的內容。 –