Free Online Tutorials ==>> Machine Learning || Python Programming || DBMS || OOPs using C++ || DSA || Java Programming || Linux/Unix || C Programming
Go to your University || Python Lab || DSA Lab || AI & Machine Learning Lab || Linux Lab || OOPs Lab || DBMS Lab || JAVA Lab ||| Free Online Tutorials ||| 
companies for Campus Placement || Logical Reasoning || Quantitative Aptitude || General English || Technical-MCQ and Interview Questions || HR Interview Questions
0 like 0 dislike
33 views
in Tutorial & Interview questions by Goeduhub's Expert (7.8k points)
Inserting a node at the beginning of a singly linked list

1 Answer

0 like 0 dislike
by Goeduhub's Expert (7.8k points)
 
Best answer

The code below will prompt for numbers and continue to add them to the beginning of a linked list.

/* This program will demonstrate inserting a node at the beginning of a linked list */

#include <stdio.h> 

#include <stdlib.h>

struct Node 

{  

int data;  

struct Node* next; 

};

void insert_node (struct Node **head, int nodeValue); 

void print_list (struct Node *head);

int main(int argc, char *argv[]) 

{  

struct Node* headNode;  headNode = NULL;         /* Initialize our first node pointer to be NULL. */  

size_t listSize, i;  

do 

{    

printf("How many numbers would you like to input?\n"); 

 } 

while(1 != scanf("%zu", &listSize));

for (i = 0; i < listSize; i++) 

{    

int numToAdd;    

do 

{      

printf("Enter a number:\n");    

while (1 != scanf("%d", &numToAdd));

insert_node (&headNode, numToAdd);    

printf("Current list after your inserted node: \n");    

print_list(headNode);  

}

return 0; 

}

void print_list (struct Node *head) 

{  

struct node* currentNode = head;

  /* Iterate through each link. */  

while (currentNode != NULL) 

{      

printf("Value: %d\n", currentNode->data);      

currentNode = currentNode -> next;  

}

void insert_node (struct Node **head, int nodeValue) 

{  

struct Node *currentNode = malloc(sizeof *currentNode);  

currentNode->data = nodeValue;  

currentNode->next = (*head);

*head = currentNode; }

Explanation for the Insertion of Nodes

In order to understand how we add nodes at the beginning, let's take a look at possible scenarios:

The list is empty, so we need to add a new node. In which case, our memory looks like this where HEAD is a1. pointer to the first node:

| HEAD | --> NULL

The line currentNode->next = *headNode; will assign the value of currentNode->next to be NULL since headNode originally starts out at a value of NULL.

Now, we want to set our head node pointer to point to our current node.

  -----             ------------

|HEAD | --> |CURRENTNODE| --> NULL /* The head node points to the current node */

-----               ------------

This is done with *headNode = currentNode;

The list is already populated; we need to add a new node to the beginning. For the sake of simplicity, let's2. start out with 1 node:

 -----             ----------

HEAD --> FIRST NODE --> NULL 

-----              ----------

With currentNode->next = *headNode, the data structure looks like this:

 ---------                -----                  --------------------

currentNode -->  HEAD --> POINTER TO FIRST NODE --> NULL 

---------                 -----                  --------------------

Which, obviously needs to be altered since *headNode should point to currentNode.

 ----             -----------            --------------

HEAD -> currentNode -->     NODE       -> NULL 

----               -----------           --------------

This is done with *headNode = currentNode;

  Realize your learning potential with courses starting at ₹ 420
 Placements:   List of companies | Logical Reasoning Questions | Quantitative Aptitude Questions | General English Questions | Technical-MCQ and Interview Questions
 Online Free Training:  MACHINE LEARNINGPython Programming | Database Management System(DBMS) | Object Oriented Programming(OOPs) using C++ | Data Structures and Algorithms(DSA) | Java Programming | Linux/Unix | C Programming
Exams: List of Exams After Graduation | List of Engineering Entrance Examinations (UG/PG) | JEE Main | JEE Advanced | GATE | IES | ISROList of PSUs
 Download Previous Year Papers For:  GATE | IES | RAJASTHAN TECHNICAL UNIVERSITY (RTU-Kota)RPSC Technical Exams | ISRO
 Goeduhub
About Us | Contact Us   Social::   |  | 
...