SlideShare a Scribd company logo
1 of 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

More Related Content

What's hot

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
 

What's hot (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
 

Similar to 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
 

Similar to 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
 

Recently uploaded

Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
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
 
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
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
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
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
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
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
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
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 

Recently uploaded (20)

Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
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
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
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
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
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
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
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
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 

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