I'm learning programming in C language and I face some troubles, especially when working with pointers. It's a little bit difficult for me since we don't use pointers in Java or C#.
What I try to do is to create a linked list (code found on the internet) and to push elements in it. Like in the code below.
What happens is that when I uncomment the second line of code, the code works but I receive the following list as answer {0, 1, 2}, even if I don't push the number 0 in the list. I would like to have this as answer: {1, 2}.
int main (){
node_t * test_list = NULL;
//test_list = malloc(sizeof(node_t));
push(test_list, 1);
push(test_list, 2);
print_list(test_list);
return 0;
}
This is how the code looks like:
typedef struct node
{
int val;
struct node * next;
} node_t;
void print_list(node_t * head)
{
node_t * current = head;
while (current != NULL)
{
printf("%d\n", current->val);
current = current->next;
}
}
node_t* new_node(node_t * head)
{
node_t * head2 = malloc(sizeof(node_t));
return head2;
}
void push(node_t * head, int val)
{
if (head == NULL)
{
head = new_node(head);
head->val = val;
head->next = NULL;
}
else
{
node_t * current = head;
while (current->next != NULL)
current = current->next;
/* now we can add a new variable */
current->next = malloc(sizeof(node_t));
current->next->val = val;
current->next->next = NULL;
}
}
In the push function, I decided to check whether the head is equal to NULL or not. If it's the case, I just want to create a new node and assign it to it. I don't know if it's a good approach. Nevertheless, it is not working.
I would be thankful if someone could guide me to the right path!
Thank you!
(Source of the code: http://www.learn-c.org/en/Linked_lists )
headinpushis not finding its way back to the caller, because you pass it a copy .//test_list = malloc(sizeof(node_t));from the main function, it adds an extra element to the list (the element 0), which I don't want. That's the reason why I tried to make it work with the functionnew_node(...), but it is not working.