When I try assign value to *temp
, it doesn't assign the value (when I'm compiling, it doesn't show the printf and by printf can't see any value assigned). Why ? How can I handle more about pointer (see where they're referencing with outer application from my IDE...?)
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#define INT_SIZE sizeof(int) * 8
typedef struct Node Node;
struct Node
{
int value;
Node *next;
};
typedef struct LinkedList
{
Node *head;
}LinkedList;
void Insert(LinkedList **lst, int data)
{
Node *temp = malloc(sizeof(Node));
//Check's if is the first Node.
if ((*lst)->head->next== NULL)
{
(*lst)->head->next = temp;
temp->value = data;
printf("Ok");
temp->next = NULL;
}
}
And my main function:
int main()
{
LinkedList *list = malloc(sizeof(LinkedList)); //Create new linkedlist
list->head->next = NULL; //Define the head object
Insert(&list, 20);
return 0;
}
There are a lot of errors in your code
In main :
LinkedList *list = malloc(sizeof(LinkedList)); //Create new linkedlist list->head->next = NULL; //Define the head object
is wrong because list->head
is not initialized, so to set list->head->next
has an undefined behavior
There is also a problem of logic, an empty list is empty => no node, the right initialization is :
list->head = NULL;
In Insert :
if ((*lst)->head->next== NULL)
again this is invalid in case the list is empty because (*lst)->head
is NULL (after the correction above).
Also there is no else branch, the function must always insert the new node.
To implement in the right way it is needed to know where the insert must be done, is your list a fifo, a lifo, or nodes are sorted depending on the value ?
Supposing a node is always inserted on the head :
void Insert(LinkedList **lst, int data)
{
Node *temp = malloc(sizeof(*temp));
temp->value = data;
temp->next = (*lst)->head;
(*lst)->head = temp;
}
Note it is useless to use your double pointer, you can have :
void Insert(LinkedList *lst, int data)
{
Node *temp = malloc(sizeof(*temp));
temp->value = data;
temp->next = lst->head;
lst->head = temp;
}
int main()
{
LinkedList *list = malloc(sizeof(*list)); //Create new linkedlist
list->head = NULL;
Insert(list, 20);
return 0;
}
Finally :
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int value;
struct Node *next;
} Node;
typedef struct LinkedList {
Node *head;
} LinkedList;
void Insert(LinkedList *lst, int data)
{
Node *temp = malloc(sizeof(*temp));
temp->value = data;
temp->next = lst->head;
lst->head = temp;
}
void pr(const LinkedList *lst)
{
const Node * l = lst->head;
while (l != NULL) {
printf("%d ", l->value);
l = l->next;
}
putchar('\n');
}
int main()
{
LinkedList *list = malloc(sizeof(*list)); //Create new linkedlist
list->head = NULL;
Insert(list, 20);
pr(list);
Insert(list, 10);
pr(list);
return 0;
}
Compilation and execution :
/tmp % gcc -Wall l.c
/tmp % ./a.out
20
10 20
/tmp %