[英]Traversing a Linked List
我是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;
}
我感到困惑的是,“ start-> next”的輸出不是NULL,而是一個固定的常量地址。 但是我在for循環之前將NULL分配給了start-> next,並且只更改了“ list”中的組件(list-> item和list-> next),而不是“ start”中的組件。 那么,為什么“啟動”中的組件被更改了?
請記住,您具有: list = start
:它們然后都指向同一個節點,只要它們相等, list->next
與start->next
相同。
在for
第一次迭代start
和list
仍然是平等的, start->next
:直到你分配將是NULL list->next = ...
。 第一次分配后,將修改start->next
指向已分配的地址。 在下一次迭代中, 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
等等
這是因為如果這項作業-
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 */
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.