2016-07-07 95 views
0

我是C新手,現在我正在學習鏈表的基礎知識。以下代碼只是遍歷鏈表的段。遍歷鏈表

#include <stdio.h> 
#include <stdlib.h> 


struct node 
{ 
    int item; 
    struct node *next; 
}; 

int main() 
{ 
    struct node *start,*list; 
    int i; 
    start = (struct node *)malloc(sizeof(struct node)); 
    list = start; 
    start->next = NULL; 


    for(i=0;i<10;i++) 
    { 
     list->item = i; 
     printf("%p\t%p\n",start->next,list->next); 
     list->next = (struct node *)malloc(sizeof(struct node)); 
     list = list->next; 
    } 

    return 0; 
} 

我很困惑,「開始 - >下一步」的輸出不是NULL,而是一個固定的常量地址。但是我在for循環之前給NULL分配了start-> next,並且只更改了「list」(list-> item和list-> next)中的組件,而不是「start」中的組件。那麼爲什麼「開始」中的組件改變了?

+0

應該是'的printf( 「%P \噸%P \ n」 個,(無效*)開始 - >下一個,(void *)list-> next);' – LPs

+0

它在最初的迭代中* *爲NULL,或者您沒有注意到它? – WhozCraig

回答

4

請記住,您有:list = start:然後它們都指向相同的節點,只要它們相等,list->nextstart->next相同。

for第一次迭代startlist仍然是平等的,直到你分配start->next將是NULL:list->next = ...。 第一次分配後,start->next將被修改爲指向malloced地址。 在下一次迭代中,list指向其他地方,並且修改list->next不會影響start->next


一步一步:( 「節點X」 是我給通過的malloc分配的節點的名稱,它們不是變量在你的程序)

node 0: { .item = ?, .next = NULL } <---- start, list 

i = 0; 
list->item = i; 

node 0: { .item = 0, .next = NULL } <---- start, list 

list->next = malloc(...) 

node 0: { .item = 0, .next = &(node 1) } <---- start, list 
node 1: { .item = ?, .next = ?   } <---- start->next, list->next 

list = list->next 

node 0: { .item = 0, .next = &(node 1) } <---- start 
node 1: { .item = ?, .next = ?   } <---- start->next, list 

i = 1; 
list->item = i; 

node 0: { .item = 0, .next = &(node 1) } <---- start 
node 1: { .item = 1, .next = ?   } <---- start->next, list 

list->next = malloc(...) 

node 0: { .item = 0, .next = &(node 1) } <---- start 
node 1: { .item = 1, .next = &(node 2) } <---- start->next, list 
node 2: { .item = ?, .next = ?   } <---- list->next 

list = list->next; 

node 0: { .item = 0, .next = &(node 1) } <---- start 
node 1: { .item = 1, .next = &(node 2) } <---- start->next 
node 2: { .item = ?, .next = ?   } <---- list 

+0

「** _在下一個迭代列表中指向其他位置,並且修改列表 - >下一個不會影響開始 - >下一個。**」。你能詳細解釋一下嗎?這是否表明linked_list在此之後停用? – ameyCU

+0

@ameyCU,我在回答中增加了一步一步的描述 - 我希望這個想法和記號很清楚 – sinelaw

+0

感謝您採取這種麻煩,但是我問的是上面的行意味着'start-> next-> next '會不同於'list-> next-> next'? – ameyCU

2

這是因爲如果該勘定

list = start; 

list指向同一個地址,這start指向,因此在該位置所做的更改與兩個指針相同(因爲它們指向相同的內存位置)。

它是與此相同實例(也許更簡單,因爲代碼) -

int a; 
int *p1,*p2; 
p1=&a; 
p2=p1; 
*p1=5; 
prinf("value : p1=%d p2=%d",*p1, *p2); 
/* Both the pointer will have same value as change is made at memory location */