I have written some code to create a singly linked list of integers and print out the items. After printing out all the items in the list, I printed out "head->item" and got the value of the integer in the first node.
I am quite puzzled as to why I can do that, because in the print() function, I wrote "head = head->next", so that means that head is changed right?
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;
}
}