Data Structures Linked List Concepts
Doubly Linked List
Dr. S. KANNIMUTHU SUBRAMANIAN
TECHNICAL PLACEMENT TRAINING
What is Doubly Linked List
• Each node in a Linked List consists of data and
address of next data & address of previous
data.
ADDRESS OF ADDRESS OF NEXT
PREVIOUS NODE DATA NODE
Doubly Linked List
Operations
Operations
Insert Delete Search
Begin End Middle Begin End Middle
Start with
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
struct node *prev;
};
struct node *head=NULL,*tail=NULL;
Insert at Begin
• Start->prev=tmp
Insert Begin
void insert_begin(int x)
{
//node creation
struct node *n=(struct node *)malloc(sizeof(struct node));
n->data=x;
n->next=NULL;
n->prev=NULL;
if(head==NULL) //if list empty
{
head=tail=n;
} Running Time!?
else // if list has elements already
{
n->next=head;
head->prev=n;
head=n;
}
}
Insert at End
Insert End
void insert_end(int x)
{
//node creation
struct node *n=(struct node *)malloc(sizeof(struct node));
n->data=x;
n->next=NULL;
n->prev=NULL;
if(head==NULL) //if list empty
{
head=tail=n;
Running Time!?
}
else // if list has elements already
{
tail->next=n;
n->prev=tail;
tail=n;
}
}
Insert at Middle
Insert Middle
void insert_middle(int x,int pos)
{
struct node *n=(struct node *)malloc(sizeof(struct node)); Running Time!?
n->data=x;
n->next=NULL;
n->prev=NULL;
if(pos==1)
insert_begin(x);
else
{
int p;
struct node *i=head;
for(p=1;p<pos-1;p++)
i=i->next;
n->next=i->next;
n->prev=i;
i->next=n;
n->next->prev=n;
}
}
Display
void display()
{
struct node *i; Running Time!?
for(i=head;i!=NULL;i=i->next)
{
printf("%d-->",i->data);
}
}
Display in Reverse
void display()
{
struct node *i; Running Time!?
for(i=tail;i!=NULL;i=i->prev)
{
printf("%d-->",i->data);
}
}
Delete at Begin
Delete End
• Make tail=tail->prev and set tail->next=NULL
head tail
Delete Middle
• It is an exercise for you!!
Search
• It is similar to the implementation in Singly
Linked List
Thank You