Reputation: 1
LinkedList.c
#include "stdio.h"
#include "stdlib.h"
struct ListNode
{
int val;
struct ListNode *next;
};
int main()
{
int a[] = {1, 2, 3};
struct ListNode *head = malloc(sizeof(struct ListNode));
head->next = NULL;
struct ListNode *rear = head;
for (int i = 0; i < 3; i++)
{
struct ListNode s;
s.val = a[i];
s.next = rear->next;
rear->next = &s;
rear = &s;
}
struct ListNode *tmp = head;
head = head->next;
free(tmp);
//display
while (head != NULL)
{
printf("%d ",(*head).val);
head = head->next;
}
return 0;
}
If I change the sentece "struct ListNode s;" to "struct ListNode *s=malloc(sizeof(struct ListNode));" and use "->" but not ".", it will work.
Upvotes: 0
Views: 50
Reputation: 5882
As pointed out in comments, you're facing this because ListNode
you create in your list creation loop is a local variable limited to loop scope. It only exists in that scope(for that particular iteration). You should use malloc
for allocating ListNode
and use free
to de-allocate memory for your nodes when you're done with using the list. I did minor changes to your list creation loop:
for (int i = 0; i < 3; i++) {
struct ListNode *s = malloc(sizeof(struct ListNode));
s->val = a[i];
s->next = rear->next;
rear->next = s;
rear = s;
}
When I ran this, I was able to see expected results:
src : $ gcc initializelinkedlist.c
src : $ ./a.out
1 2 3
Upvotes: 1