【发布时间】:2014-04-29 22:32:14
【问题描述】:
我已经编写了一些代码来创建一个整数的单链表并打印出这些项目。打印出列表中的所有项目后,我打印出“head->item”并得到第一个节点中整数的值。
我很纳闷为什么我可以这样做,因为在 print() 函数中,我写了“head = head->next”,所以这意味着 head 被改变了对吧?
main()
int n;
int value;
ListNode *head = NULL;
ListNode *temp = NULL;
printf("Enter a value: ");
scanf("%d", &n);
while (n != -1)
{
if (head == NULL)
{
head = malloc(sizeof(ListNode));//create the head first
temp = head;//get temp to have the same value as head, so we do not accidently edit head
}
else
{
temp->next = malloc(sizeof(ListNode));//allocate space for the next node
temp = temp->next;//let temp be the next node
}
temp->item = n;//allocate a value for the node
temp->next = NULL;//specify a NULL value for the next node so as to be able to allocate space
scanf("%d", &n);
}
print(head);
printf("%d\n", head->item);//why can I still get the integer in the first node
while (head != NULL)
{
temp = head;
head = head->next;
free(temp);
}
head = NULL;
return 0;
}
void print(ListNode *head)
{
if (head == NULL)
{
return;
}
while (head != NULL)
{
printf("%i\n", head->item);
head = head->next;
}
}
【问题讨论】:
-
headprint 函数的变量改变了,但main函数的变量没有改变
标签: c pointers linked-list