# Program to show insertion of node at beginning in singly linked list

0 like 1 dislike
4.0k views

edited
Program to show insertion of node at beginning in singly linked list

0 like 0 dislike
by Goeduhub's Expert (7.6k points)
edited

## 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;

};

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;

};

void display()

{

struct node *ptr;

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;

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

Learn & Improve In-Demand Data Skills Online in this Summer With  These High Quality Courses[Recommended by GOEDUHUB]:-

Best Data Science Online Courses[Lists] on:-

Claim your 10 Days FREE Trial for Pluralsight.