I have explained where I'm currently stuck at the bottom.
This structure below is my node .
struct node {
int data;
struct node *next;
}
struct node *head;
I have already alocated memory to head node.
head = malloc(sizeof(struct node));
And created a bunch of other nodes linked to it by
struct node *temp;
for (int i=0; i < no_of_nodes - 1; i++)
{
struct node *n = malloc(sizeof(struct node));
temp -> next = n;
printf("Enter Node %d data : ", i+1);
scanf("%d", &(n -> data));
temp = n;
}
temp -> next = NULL;
Then my printNodes function
void printNodes(struct node *n)
{
//printf("%d", n -> data);
while(n != NULL)
{
if (n -> next != NULL)
printf("%d%s", n -> data, " -> ");
else
printf("%d%s", n -> data, " -> NULL\n");
n = n->next;
}
}
The output will look like : 6 -> 7 -> 8 -> 9 -> 3 -> NULL
Now, i'm trying to insert a node at head node, i.e it becomes the head node and the original head becomes the second node.
printf("Enter the head position (obviously 0) : ");
scanf("%d", &pos);
insertNode(head, pos);
printNodes(head);
The insertNode function :
void insertNode (struct node *head, int pos)
{
struct node *n;
n = malloc(sizeof(struct node));
printf("Enter the Node data : ");
scanf("%d", &(n -> data));
if (pos == 0)
{
printf("Pos was 0, so HEAD\n");
n -> next = head;
head = n;
printNodes(head);
}
}
Ok, so the problem is that, the printNodes(head) actually prints the as intended..
but the
printNodes(head);after insertNodes(head, pos) doesn't print the updated Linked List,
why is the head not being updated ?
Where did I do wrong ?
The output I get is, Output:
Enter the Head position (obviously 0) : 0
Enter the Node data : 34
Pos was 0, so HEAD
34 -> 6 -> 7 -> 8 -> 9 -> 3 -> NULL [from printNodes(head) inside insertNodes(head, pos)]
6 -> 7 -> 8 -> 9 -> 3 -> NULL [from printNodes(head) after insertNodes(head, pos)]
If anyone wants to look at the full code, here you go.
Any help is appreciated.. Thank you in advance.