Program to show insertion of node at beginning
A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations.

- A node contains two fields i.e. data stored at that particular address and the pointer which contains the address of the next node in the memory.
- The last node of the list contains pointer to the null.
The simplest kind of linked list is a singly liked list (SLL) which has one link per node. It has two parts, one part contains data and other contains address of next node. In simple words, a linked list consists of nodes where each node contains a data field and a reference(link) to the next node in the list.The structure of a node in a SLL is given as in C:
struct node { int data; struct node *next; }; struct node *head, *ptr; ptr = (struct node *)malloc(sizeof(struct node *)); |
---|
Algorithm to insert a node at beginning
Step 1: IF PTR = NULL Write OVERFLOW Go to Step 7 [END OF IF] Step 2: SET NEW_NODE = PTR Step 3: SET PTR = PTR → NEXT Step 4: SET NEW_NODE → DATA = VAL Step 5: SET NEW_NODE → NEXT = HEAD Step 6: SET HEAD = NEW_NODE Step 7: EXIT |
---|
Example

Program
#include <stdio.h> #include<conio.h> #include<stdlib.h> void front(int); struct node { int data; struct node *next; }; struct node *head; void display() { struct node *ptr; ptr = head; if(ptr == NULL) { printf("Nothing to print"); } else { printf("\nprinting values . . . . .\n"); while (ptr!=NULL) { printf("\n%d",ptr->data); ptr = ptr -> next; } } } void front(int item) { struct node *ptr = (struct node *)malloc(sizeof(struct node *)); if(ptr == NULL) { printf("\nOVERFLOW !!!\n"); } else { ptr->data = item; ptr->next = head; head = ptr; printf("\nGiven node is inserted\n"); } } void main () { int item; printf("\nEnter the item which you want to insert?\n"); scanf("%d",&item); front(item); display(); } |
---|
Output

For more Manipal University Jaipur B.Tech CSE-III Sem Data Structure Lab Experiments Click here