SlideShare ist ein Scribd-Unternehmen logo
1 von 6
**
* C program to insert a node in Doubly linked list
*/
#include <stdio.h>
#include <stdlib.h>
/*
* Basic structure of Node
*/
struct node {
int data;
struct node * prev;
struct node * next;
}*head, *last;
/*
* Function used in this program
*/
void createList(int n);
void displayList();
void insertAtBeginning(int data);
void insertAtEnd(int data);
void insertAtN(int data, int position);
int main()
{
int n, data, choice=1;
head = NULL;
last = NULL;
/*
* Run forever until user chooses 0
*/
while(choice != 0)
{
/*
* Menu creation to use the program
*/
printf("============================================n");
printf("DOUBLY LINKED LIST PROGRAMn");
printf("============================================n");
printf("1. Create Listn");
printf("2. Insert node - at beginningn");
printf("3. Insert node - at endn");
printf("4. Insert node - at Nn");
printf("5. Display listn");
printf("0. Exitn");
printf("--------------------------------------------n");
printf("Enter your choice : ");
scanf("%d", &choice);
/*
* Choose from different menu operation
*/
switch(choice)
{
case 1:
printf("Enter the total number of nodes in list: ");
scanf("%d", &n);
createList(n);
break;
case 2:
printf("Enter data of first node : ");
scanf("%d", &data);
insertAtBeginning(data);
break;
case 3:
printf("Enter data of last node : ");
scanf("%d", &data);
insertAtEnd(data);
break;
case 4:
printf("Enter the position where you want to insert new node: ");
scanf("%d", &n);
printf("Enter data of %d node : ", n);
scanf("%d", &data);
insertAtN(data, n);
break;
case 5:
displayList();
break;
case 0:
break;
default:
printf("Error! Invalid choice. Please choose between 0-5");
}
printf("nnnnn");
}
return 0;
}
/**
* Creates a doubly linked list of n nodes.
* @n Number of nodes to be created
*/
void createList(int n)
{
int i, data;
struct node *newNode;
if(n >= 1)
{
/*
* Create and link the head node
*/
head = (struct node *)malloc(sizeof(struct node));
printf("Enter data of 1 node: ");
scanf("%d", &data);
head->data = data;
head->prev = NULL;
head->next = NULL;
last = head;
/*
* Create and link rest of the n-1 nodes
*/
for(i=2; i<=n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));
printf("Enter data of %d node: ", i);
scanf("%d", &data);
newNode->data = data;
newNode->prev = last; // Link new node with the previous node
newNode->next = NULL;
last->next = newNode; // Link previous node with the new node
last = newNode; // Make new node as last/previous node
}
printf("nDOUBLY LINKED LIST CREATED SUCCESSFULLYn");
}
}
/**
* Display content of the list from beginning to end
*/
void displayList()
{
struct node * temp;
int n = 1;
if(head == NULL)
{
printf("List is empty.n");
}
else
{
temp = head;
printf("DATA IN THE LIST:n");
while(temp != NULL)
{
printf("DATA of %d node = %dn", n, temp->data);
n++;
/* Move the current pointer to next node */
temp = temp->next;
}
}
}
/**
* Inserts a new node at the beginning of the doubly linked list
* @data Data of the first node i.e. data of the new node
*/
void insertAtBeginning(int data)
{
struct node * newNode;
if(head == NULL)
{
printf("Error, List is Empty!n");
}
else
{
newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = data;
newNode->next = head; // Point to next node which is currently head
newNode->prev = NULL; // Previous node of first node is NULL
/* Link previous address field of head with newnode */
head->prev = newNode;
/* Make the new node as head node */
head = newNode;
printf("NODE INSERTED SUCCESSFULLY AT THE BEGINNING OF THE LISTn");
}
}
/**
* Inserts a new node at the end of the doubly linked list
* @data Data of the last node i.e data of the new node
*/
void insertAtEnd(int data)
{
struct node * newNode;
if(last == NULL)
{
printf("Error, List is empty!n");
}
else
{
newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = data;
newNode->next = NULL;
newNode->prev = last;
last->next = newNode;
last = newNode;
printf("NODE INSERTED SUCCESSFULLY AT THE END OF LISTn");
}
}
/**
* Inserts a node at any position in the doubly linked list
* @data Data of the new node to be inserted
* @position Position where to insert the new node
*/
void insertAtN(int data, int position)
{
int i;
struct node * newNode, *temp;
if(head == NULL)
{
printf("Error, List is empty!n");
}
else
{
temp = head;
i=1;
while(i<position-1 && temp!=NULL)
{
temp = temp->next;
i++;
}
if(position == 1)
{
insertAtBeginning(data);
}
else if(temp == last)
{
insertAtEnd(data);
}
else if(temp!=NULL)
{
newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = data;
newNode->next = temp->next; // Connect new node with n+1th node
newNode->prev = temp; // Connect new node with n-1th node
if(temp->next != NULL)
{
/* Connect n+1th node with new node */
temp->next->prev = newNode;
}
/* Connect n-1th node with new node */
temp->next = newNode;
printf("NODE INSERTED SUCCESSFULLY AT %d POSITIONn", position);
}
else
{
printf("Error, Invalid positionn");
}
}
}
Output

Weitere ähnliche Inhalte

Was ist angesagt?

B trees in Data Structure
B trees in Data StructureB trees in Data Structure
B trees in Data StructureAnuj Modi
 
queue & its applications
queue & its applicationsqueue & its applications
queue & its applicationssomendra kumar
 
Data Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search TreeData Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search TreeManishPrajapati78
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Treesagar yadav
 
SEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMSSEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMSGokul Hari
 
1.1 binary tree
1.1 binary tree1.1 binary tree
1.1 binary treeKrish_ver2
 
Array in c language
Array in c languageArray in c language
Array in c languagehome
 
Queue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListQueue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListPTCL
 
Array implementation and linked list as datat structure
Array implementation and linked list as datat structureArray implementation and linked list as datat structure
Array implementation and linked list as datat structureTushar Aneyrao
 
Binary Heap Tree, Data Structure
Binary Heap Tree, Data Structure Binary Heap Tree, Data Structure
Binary Heap Tree, Data Structure Anand Ingle
 
B trees and_b__trees
B trees and_b__treesB trees and_b__trees
B trees and_b__treesmeghu123
 

Was ist angesagt? (20)

Linear data structure concepts
Linear data structure conceptsLinear data structure concepts
Linear data structure concepts
 
1.7 avl tree
1.7 avl tree 1.7 avl tree
1.7 avl tree
 
B trees in Data Structure
B trees in Data StructureB trees in Data Structure
B trees in Data Structure
 
queue & its applications
queue & its applicationsqueue & its applications
queue & its applications
 
Data Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search TreeData Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search Tree
 
Linked List
Linked ListLinked List
Linked List
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Singly link list
Singly link listSingly link list
Singly link list
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
SEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMSSEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMS
 
Stack using Array
Stack using ArrayStack using Array
Stack using Array
 
1.1 binary tree
1.1 binary tree1.1 binary tree
1.1 binary tree
 
Array in c language
Array in c languageArray in c language
Array in c language
 
Binary search tree(bst)
Binary search tree(bst)Binary search tree(bst)
Binary search tree(bst)
 
Stacks and Queue - Data Structures
Stacks and Queue - Data StructuresStacks and Queue - Data Structures
Stacks and Queue - Data Structures
 
Queue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListQueue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked List
 
Array implementation and linked list as datat structure
Array implementation and linked list as datat structureArray implementation and linked list as datat structure
Array implementation and linked list as datat structure
 
Binary Heap Tree, Data Structure
Binary Heap Tree, Data Structure Binary Heap Tree, Data Structure
Binary Heap Tree, Data Structure
 
B trees and_b__trees
B trees and_b__treesB trees and_b__trees
B trees and_b__trees
 
Binary tree
Binary treeBinary tree
Binary tree
 

Ähnlich wie C program to insert a node in doubly linked list

THE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdf
THE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdfTHE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdf
THE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdffathimahardwareelect
 
C code on linked list #include stdio.h #include stdlib.h.pdf
 C code on linked list #include stdio.h #include stdlib.h.pdf C code on linked list #include stdio.h #include stdlib.h.pdf
C code on linked list #include stdio.h #include stdlib.h.pdfdeepua8
 
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjhlinked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjhvasavim9
 
How to do insertion sort on a singly linked list with no header usin.pdf
How to do insertion sort on a singly linked list with no header usin.pdfHow to do insertion sort on a singly linked list with no header usin.pdf
How to do insertion sort on a singly linked list with no header usin.pdfarihantelehyb
 
Program to insert in a sorted list #includestdio.h#include.pdf
 Program to insert in a sorted list #includestdio.h#include.pdf Program to insert in a sorted list #includestdio.h#include.pdf
Program to insert in a sorted list #includestdio.h#include.pdfsudhirchourasia86
 
1#include stdio.h#include stdlib.h#include assert.h .pdf
1#include stdio.h#include stdlib.h#include assert.h .pdf1#include stdio.h#include stdlib.h#include assert.h .pdf
1#include stdio.h#include stdlib.h#include assert.h .pdfsudhinjv
 
C++Write a method Node Nodereverse() which reverses a list..pdf
C++Write a method Node Nodereverse() which reverses a list..pdfC++Write a method Node Nodereverse() which reverses a list..pdf
C++Write a method Node Nodereverse() which reverses a list..pdfarjunenterprises1978
 
tested on eclipseDoublyLinkedList class.pdf
tested on eclipseDoublyLinkedList class.pdftested on eclipseDoublyLinkedList class.pdf
tested on eclipseDoublyLinkedList class.pdfshanki7
 
Write java program using linked list to get integer from user and.docx
 Write java program using linked list to get integer from user and.docx Write java program using linked list to get integer from user and.docx
Write java program using linked list to get integer from user and.docxajoy21
 
hi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdfhi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdfarchgeetsenterprises
 
A)B) C++ program to create a Complete Binary tree from its Lin.pdf
A)B) C++ program to create a Complete Binary tree from its Lin.pdfA)B) C++ program to create a Complete Binary tree from its Lin.pdf
A)B) C++ program to create a Complete Binary tree from its Lin.pdfanton291
 
mainpublic class AssignmentThree {    public static void ma.pdf
mainpublic class AssignmentThree {    public static void ma.pdfmainpublic class AssignmentThree {    public static void ma.pdf
mainpublic class AssignmentThree {    public static void ma.pdffathimafancyjeweller
 
This assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdfThis assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdfEricvtJFraserr
 
Write a program to implement below operations with both singly and d.pdf
Write a program to implement below operations with both singly and d.pdfWrite a program to implement below operations with both singly and d.pdf
Write a program to implement below operations with both singly and d.pdfthangarajarivukadal
 
Lab Week 2 Game Programming.docx
Lab Week 2 Game Programming.docxLab Week 2 Game Programming.docx
Lab Week 2 Game Programming.docxteyaj1
 
Using the provided table interface table.h and the sample linked lis.pdf
Using the provided table interface table.h and the sample linked lis.pdfUsing the provided table interface table.h and the sample linked lis.pdf
Using the provided table interface table.h and the sample linked lis.pdfconnellalykshamesb60
 
Write a program in C that does the followinga) Builds a simple li.pdf
Write a program in C that does the followinga) Builds a simple li.pdfWrite a program in C that does the followinga) Builds a simple li.pdf
Write a program in C that does the followinga) Builds a simple li.pdfkavithaarp
 

Ähnlich wie C program to insert a node in doubly linked list (20)

THE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdf
THE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdfTHE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdf
THE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdf
 
C code on linked list #include stdio.h #include stdlib.h.pdf
 C code on linked list #include stdio.h #include stdlib.h.pdf C code on linked list #include stdio.h #include stdlib.h.pdf
C code on linked list #include stdio.h #include stdlib.h.pdf
 
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjhlinked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
 
How to do insertion sort on a singly linked list with no header usin.pdf
How to do insertion sort on a singly linked list with no header usin.pdfHow to do insertion sort on a singly linked list with no header usin.pdf
How to do insertion sort on a singly linked list with no header usin.pdf
 
Program to insert in a sorted list #includestdio.h#include.pdf
 Program to insert in a sorted list #includestdio.h#include.pdf Program to insert in a sorted list #includestdio.h#include.pdf
Program to insert in a sorted list #includestdio.h#include.pdf
 
1#include stdio.h#include stdlib.h#include assert.h .pdf
1#include stdio.h#include stdlib.h#include assert.h .pdf1#include stdio.h#include stdlib.h#include assert.h .pdf
1#include stdio.h#include stdlib.h#include assert.h .pdf
 
week-13x
week-13xweek-13x
week-13x
 
C++Write a method Node Nodereverse() which reverses a list..pdf
C++Write a method Node Nodereverse() which reverses a list..pdfC++Write a method Node Nodereverse() which reverses a list..pdf
C++Write a method Node Nodereverse() which reverses a list..pdf
 
tested on eclipseDoublyLinkedList class.pdf
tested on eclipseDoublyLinkedList class.pdftested on eclipseDoublyLinkedList class.pdf
tested on eclipseDoublyLinkedList class.pdf
 
Write java program using linked list to get integer from user and.docx
 Write java program using linked list to get integer from user and.docx Write java program using linked list to get integer from user and.docx
Write java program using linked list to get integer from user and.docx
 
hi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdfhi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdf
 
A)B) C++ program to create a Complete Binary tree from its Lin.pdf
A)B) C++ program to create a Complete Binary tree from its Lin.pdfA)B) C++ program to create a Complete Binary tree from its Lin.pdf
A)B) C++ program to create a Complete Binary tree from its Lin.pdf
 
mainpublic class AssignmentThree {    public static void ma.pdf
mainpublic class AssignmentThree {    public static void ma.pdfmainpublic class AssignmentThree {    public static void ma.pdf
mainpublic class AssignmentThree {    public static void ma.pdf
 
This assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdfThis assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdf
 
Lab-2.4 101.pdf
Lab-2.4 101.pdfLab-2.4 101.pdf
Lab-2.4 101.pdf
 
Write a program to implement below operations with both singly and d.pdf
Write a program to implement below operations with both singly and d.pdfWrite a program to implement below operations with both singly and d.pdf
Write a program to implement below operations with both singly and d.pdf
 
Lab Week 2 Game Programming.docx
Lab Week 2 Game Programming.docxLab Week 2 Game Programming.docx
Lab Week 2 Game Programming.docx
 
Using the provided table interface table.h and the sample linked lis.pdf
Using the provided table interface table.h and the sample linked lis.pdfUsing the provided table interface table.h and the sample linked lis.pdf
Using the provided table interface table.h and the sample linked lis.pdf
 
Write a program in C that does the followinga) Builds a simple li.pdf
Write a program in C that does the followinga) Builds a simple li.pdfWrite a program in C that does the followinga) Builds a simple li.pdf
Write a program in C that does the followinga) Builds a simple li.pdf
 
DSA(1).pptx
DSA(1).pptxDSA(1).pptx
DSA(1).pptx
 

Kürzlich hochgeladen

Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 

Kürzlich hochgeladen (20)

Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 

C program to insert a node in doubly linked list

  • 1. ** * C program to insert a node in Doubly linked list */ #include <stdio.h> #include <stdlib.h> /* * Basic structure of Node */ struct node { int data; struct node * prev; struct node * next; }*head, *last; /* * Function used in this program */ void createList(int n); void displayList(); void insertAtBeginning(int data); void insertAtEnd(int data); void insertAtN(int data, int position); int main() { int n, data, choice=1; head = NULL; last = NULL; /* * Run forever until user chooses 0 */ while(choice != 0) { /* * Menu creation to use the program */ printf("============================================n"); printf("DOUBLY LINKED LIST PROGRAMn"); printf("============================================n"); printf("1. Create Listn"); printf("2. Insert node - at beginningn"); printf("3. Insert node - at endn"); printf("4. Insert node - at Nn"); printf("5. Display listn"); printf("0. Exitn"); printf("--------------------------------------------n"); printf("Enter your choice : "); scanf("%d", &choice); /*
  • 2. * Choose from different menu operation */ switch(choice) { case 1: printf("Enter the total number of nodes in list: "); scanf("%d", &n); createList(n); break; case 2: printf("Enter data of first node : "); scanf("%d", &data); insertAtBeginning(data); break; case 3: printf("Enter data of last node : "); scanf("%d", &data); insertAtEnd(data); break; case 4: printf("Enter the position where you want to insert new node: "); scanf("%d", &n); printf("Enter data of %d node : ", n); scanf("%d", &data); insertAtN(data, n); break; case 5: displayList(); break; case 0: break; default: printf("Error! Invalid choice. Please choose between 0-5"); } printf("nnnnn"); } return 0; } /** * Creates a doubly linked list of n nodes. * @n Number of nodes to be created */ void createList(int n) { int i, data; struct node *newNode; if(n >= 1) { /*
  • 3. * Create and link the head node */ head = (struct node *)malloc(sizeof(struct node)); printf("Enter data of 1 node: "); scanf("%d", &data); head->data = data; head->prev = NULL; head->next = NULL; last = head; /* * Create and link rest of the n-1 nodes */ for(i=2; i<=n; i++) { newNode = (struct node *)malloc(sizeof(struct node)); printf("Enter data of %d node: ", i); scanf("%d", &data); newNode->data = data; newNode->prev = last; // Link new node with the previous node newNode->next = NULL; last->next = newNode; // Link previous node with the new node last = newNode; // Make new node as last/previous node } printf("nDOUBLY LINKED LIST CREATED SUCCESSFULLYn"); } } /** * Display content of the list from beginning to end */ void displayList() { struct node * temp; int n = 1; if(head == NULL) { printf("List is empty.n"); } else { temp = head; printf("DATA IN THE LIST:n"); while(temp != NULL) { printf("DATA of %d node = %dn", n, temp->data); n++;
  • 4. /* Move the current pointer to next node */ temp = temp->next; } } } /** * Inserts a new node at the beginning of the doubly linked list * @data Data of the first node i.e. data of the new node */ void insertAtBeginning(int data) { struct node * newNode; if(head == NULL) { printf("Error, List is Empty!n"); } else { newNode = (struct node *)malloc(sizeof(struct node)); newNode->data = data; newNode->next = head; // Point to next node which is currently head newNode->prev = NULL; // Previous node of first node is NULL /* Link previous address field of head with newnode */ head->prev = newNode; /* Make the new node as head node */ head = newNode; printf("NODE INSERTED SUCCESSFULLY AT THE BEGINNING OF THE LISTn"); } } /** * Inserts a new node at the end of the doubly linked list * @data Data of the last node i.e data of the new node */ void insertAtEnd(int data) { struct node * newNode; if(last == NULL) { printf("Error, List is empty!n"); } else { newNode = (struct node *)malloc(sizeof(struct node)); newNode->data = data; newNode->next = NULL; newNode->prev = last;
  • 5. last->next = newNode; last = newNode; printf("NODE INSERTED SUCCESSFULLY AT THE END OF LISTn"); } } /** * Inserts a node at any position in the doubly linked list * @data Data of the new node to be inserted * @position Position where to insert the new node */ void insertAtN(int data, int position) { int i; struct node * newNode, *temp; if(head == NULL) { printf("Error, List is empty!n"); } else { temp = head; i=1; while(i<position-1 && temp!=NULL) { temp = temp->next; i++; } if(position == 1) { insertAtBeginning(data); } else if(temp == last) { insertAtEnd(data); } else if(temp!=NULL) { newNode = (struct node *)malloc(sizeof(struct node)); newNode->data = data; newNode->next = temp->next; // Connect new node with n+1th node newNode->prev = temp; // Connect new node with n-1th node if(temp->next != NULL) { /* Connect n+1th node with new node */ temp->next->prev = newNode; } /* Connect n-1th node with new node */ temp->next = newNode;
  • 6. printf("NODE INSERTED SUCCESSFULLY AT %d POSITIONn", position); } else { printf("Error, Invalid positionn"); } } } Output