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

PPTX
LINKED LISTS
PPTX
Trees data structure
PDF
Algorithm and Data Structure - Queue
PPTX
Tree in data structure
PDF
2nd PUC computer science chapter 2 boolean algebra
PPT
Data Structure and Algorithms Linked List
PPTX
Unit 5 java-awt (1)
PPT
1.7 avl tree
LINKED LISTS
Trees data structure
Algorithm and Data Structure - Queue
Tree in data structure
2nd PUC computer science chapter 2 boolean algebra
Data Structure and Algorithms Linked List
Unit 5 java-awt (1)
1.7 avl tree

What's hot (20)

PPTX
trees in data structure
PDF
Trees, Binary Search Tree, AVL Tree in Data Structures
PPTX
Tree Traversal
PDF
Data Structures & Recursion-Introduction.pdf
PPT
(Binary tree)
PDF
PPTX
Linked list
PPTX
PPT
Java applets
PDF
linked lists in data structures
PPTX
B tree long
PPTX
Link list
PPTX
Collision in Hashing.pptx
PPT
B trees dbms
PPT
Tree-In Data Structure
PPTX
Data Structures - Lecture 9 [Stack & Queue using Linked List]
PPTX
Linked list
PPT
Arrays searching-sorting
PDF
AD3251-Data Structures Design-Notes-Tree.pdf
trees in data structure
Trees, Binary Search Tree, AVL Tree in Data Structures
Tree Traversal
Data Structures & Recursion-Introduction.pdf
(Binary tree)
Linked list
Java applets
linked lists in data structures
B tree long
Link list
Collision in Hashing.pptx
B trees dbms
Tree-In Data Structure
Data Structures - Lecture 9 [Stack & Queue using Linked List]
Linked list
Arrays searching-sorting
AD3251-Data Structures Design-Notes-Tree.pdf
Ad

Similar to C program to insert a node in doubly linked list (20)

PDF
THE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdf
PDF
C code on linked list #include stdio.h #include stdlib.h.pdf
DOCX
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
PDF
How to do insertion sort on a singly linked list with no header usin.pdf
PDF
Program to insert in a sorted list #includestdio.h#include.pdf
PPTX
Link List Programming Linked List in Cpp
PDF
1#include stdio.h#include stdlib.h#include assert.h .pdf
PDF
C++Write a method Node Nodereverse() which reverses a list..pdf
PDF
tested on eclipseDoublyLinkedList class.pdf
PDF
TutorialII_Updated____niceupdateprogram.pdf
DOCX
Write java program using linked list to get integer from user and.docx
PDF
hi i have to write a java program involving link lists. i have a pro.pdf
PDF
A)B) C++ program to create a Complete Binary tree from its Lin.pdf
PDF
mainpublic class AssignmentThree {    public static void ma.pdf
PDF
This assignment and the next (#5) involve design and development of a.pdf
PDF
Lab-2.4 101.pdf
DOCX
Shortened Linked List in C programming easy to learn for exam
PDF
Write a program to implement below operations with both singly and d.pdf
DOCX
Lab Week 2 Game Programming.docx
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
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
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
Link List Programming Linked List in Cpp
1#include stdio.h#include stdlib.h#include assert.h .pdf
C++Write a method Node Nodereverse() which reverses a list..pdf
tested on eclipseDoublyLinkedList class.pdf
TutorialII_Updated____niceupdateprogram.pdf
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
A)B) C++ program to create a Complete Binary tree from its Lin.pdf
mainpublic class AssignmentThree {    public static void ma.pdf
This assignment and the next (#5) involve design and development of a.pdf
Lab-2.4 101.pdf
Shortened Linked List in C programming easy to learn for exam
Write a program to implement below operations with both singly and d.pdf
Lab Week 2 Game Programming.docx
Ad

Recently uploaded (20)

PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
NOI Hackathon - Summer Edition - GreenThumber.pptx
PPTX
Onica Farming 24rsclub profitable farm business
PDF
PSYCHOLOGY IN EDUCATION.pdf ( nice pdf ...)
PPTX
Revamp in MTO Odoo 18 Inventory - Odoo Slides
PPTX
Introduction and Scope of Bichemistry.pptx
PPTX
How to Manage Starshipit in Odoo 18 - Odoo Slides
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
From loneliness to social connection charting
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Open folder Downloads.pdf yes yes ges yes
PDF
Business Ethics Teaching Materials for college
PDF
Insiders guide to clinical Medicine.pdf
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPTX
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
PPTX
COMPUTERS AS DATA ANALYSIS IN PRECLINICAL DEVELOPMENT.pptx
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Pharmacology of Heart Failure /Pharmacotherapy of CHF
NOI Hackathon - Summer Edition - GreenThumber.pptx
Onica Farming 24rsclub profitable farm business
PSYCHOLOGY IN EDUCATION.pdf ( nice pdf ...)
Revamp in MTO Odoo 18 Inventory - Odoo Slides
Introduction and Scope of Bichemistry.pptx
How to Manage Starshipit in Odoo 18 - Odoo Slides
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Anesthesia in Laparoscopic Surgery in India
From loneliness to social connection charting
102 student loan defaulters named and shamed – Is someone you know on the list?
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Open folder Downloads.pdf yes yes ges yes
Business Ethics Teaching Materials for college
Insiders guide to clinical Medicine.pdf
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
COMPUTERS AS DATA ANALYSIS IN PRECLINICAL DEVELOPMENT.pptx
Week 4 Term 3 Study Techniques revisited.pptx

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