I m trying to insert a newNode at the beginning of a linked list in C language. I have tried other methods such as returing the newNode from the insertAtBeginnning function and then setting the head as that newNode in the main function & that works fine. But what I want to do is use a void function for the case and change the head there itself which is not working. Here's the complete code :
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
void linkedListTraversal(struct Node *ptr)
{
while (ptr != NULL)
{
printf("element: %d\n", ptr->data);
ptr = ptr->next;
}
}
void insertAtBeginning(struct Node *head, int data)
{
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = head;
head = newNode;
}
void insertAtIndex(struct Node *head, int data, int index)
{
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
temp = head;
int i = 0;
while (i < index - 1)
{
temp = temp->next;
i++;
}
newNode->data = data;
newNode->next = temp->next;
temp->next = newNode;
}
void insertAtEnd(struct Node *head, int data)
{
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
temp = head;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = newNode;
newNode->data = data;
newNode->next = NULL;
}
void insertAfterNode(struct Node *previous, int data)
{
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = previous->next;
previous->next = newNode;
}
int main()
{
struct Node *head;
struct Node *second;
struct Node *third;
struct Node *fourth;
// Allocate memory for the nodes of the linkedLists in the heap
head = (struct Node *)malloc(sizeof(struct Node));
second = (struct Node *)malloc(sizeof(struct Node));
third = (struct Node *)malloc(sizeof(struct Node));
fourth = (struct Node *)malloc(sizeof(struct Node));
// Link first and second nodes
head->data = 12;
head->next = second;
// Link second and third nodes
second->data = 98;
second->next = third;
// Link third and fourth nodes
third->data = 38;
third->next = fourth;
// Terminate the linkedList at the fourth node
fourth->data = 37;
fourth->next = NULL;
printf("Linked list before insertion\n");
linkedListTraversal(head);
insertAtBeginning(head, 20);
// insertAtIndex(head, 22, 3);
// insertAtEnd(head, 110);
// insertAfterNode(second, 27);
printf("Linked list after insertion\n");
linkedListTraversal(head);
return 0;
}
Here i have also used other cases of insertion in linked list and all are working fine instead of just insertAtBeginning function :( Any help will be greatfull.