Vous êtes sur la page 1sur 31

UNIT I

DATA STRUCTURES
Data Object: A data object is a set of instances or values.
For example,
Boolean = { false, true }
Digit = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
Letter = { A, B, C,Z, a, b, c..z }
In the above examples, Boolean, Digit and Letter are the data objects which are
the set of values that are shown within the braces. The values within the braces are called
the instances of that particular data object.
Consider a data object,
Natural Number = { 1, 2, 3, }
The instances of this data object may be atomic or compound in nature. The
values 1, 2, 3, etc are atomic as they cannot be split further. But take a value 483 which
is also an instance of the data object Natural Number. 483 is a compound instance as it
can be further split into 4, 8 and 3. These are called the elements of the instance. The
elements may be instances of the same data object or it may be the instances of some
other data object.
The instances of a data object as well as the elements that constitute individual
instances are generally related in some way.
For example,
In the data object Digit, 0 may the smallest number, 1 may be the next number
and so on. This is a type of simple relationship. Take the instance 483 of the data object
Natural Number. It may be split into 4, 8 and 3, where 4 is the most significant bit, 8 is
the next and 3 is the least significant bit. This again is a simple relationship existing
between the elements of an instance.
Hence, now it must be clear that there is always some relationship existing
between the instances of a data object and between the elements of the instance. In
addition to these relationships, a set of functions is generally associated with a data
object. These functions transform one instance of an object into another instance of that
object or into an instance of another data object. The function could also create a new
instance without transforming the instance from which the new one is created.
For example, there can be a function called Add on the instances of a Natural
number data object. When Add function is applied on the instances 4 and 5, we get new
instance 9 but the original instances 4 and 5 are not disturbed. They still remain in the list
of instances of the data object.

Data Structure: A Data Structure is a data object together with the relationships that
exist among the instances and among the individual elements that compose an instance.
In other words, we define Data Structure as a way of organizing data that considers not
only the items stored but also their relationship to each other.
Once a data structure has been chosen for a particular application, they have to be
handled in an efficient way. Hence there comes the necessity of studying Algorithms.
The two categories data structures are,
1. Linear Data Structures
2. Non-linear Data Structures
Linear data structures are those in which the elements form a sequence whereas nonlinear data structures are those in which the elements do not form a sequence.

LINEAR DATA STRUCTURES


There are two methods by which we can construct a linear data structure. They
are,
Method 1: By using a sequence of memory locations. These are implemented using
arrays.
Method 2: By using pointers or links. These are implemented using linked lists.
The different types of linear data structures are:
1. Array
- The collection of similar data items grouped together which shares
the common name
2. Lists
- The list can be implemented using arrays these are called linear
lists or ordered lists.
- The list can be implemented using pointers these are called
linked lists.
3. Stacks
- The stacks can be implemented using arrays.
- The stacks can be implemented using linked.
4. Queues
- The queue can be implemented using arrays.
- The queue can be implemented using linked lists.

ARRAY
Array:
It is an ordered set which consists of fixed number of same data items. All the
data items in the set shares the common name called array name. The individual item in
the set is called an element of an array.
Whenever an array gets declared, a contiguous memory location is sequentially
allocated and the starting address will be stored in the array name.

Characteristics:
i.
ii.
iii.
iv.
v.
vi.

Array concept can be used if the same data items have to be grouped
together
Element of an array can be accessed using the array name and subscript
variable called index
The subscript variable can be treated like an ordinary variable.
The range of the index is 0 to N-1 where N is the total number of elements
in an array.
The size of the array is fixed.
Like the other variables, array also has to be declared before its usage.

Storage representation:
Whenever an array gets declared, a contiguous memory location gets allocated
and the address of the first location (Base address) gets stored in the array name.
For example the following statement can be used to allocate five contiguous
locations of type integer.
Int a[5];
The element in the array can be accessed using the array name and subscript like
a[0],a[1],.
100

102

104

106

108

2 Bytes
a

a[0]

100

a[1]

a[2]

a[3]

a[4]

The address of the element gets calculated by


a[i]= a+i*size of the data item
a[2]=a+2*2
= 100+ 4 = 104
A multidimensional array can be represented by an equivalent one-dimensional
array. For example a 2D array can be represented by an equivalent one dimensional array
by following any one of the following order
i. row major order
ii. Column major order
Row major order
The given two dimensional arrays will get stored row by row.
For example consider the two dimensional array
Int a[3][2];
It is the collection of 3 one dimensional arrays and the capacity of each one
dimensional array is two.
3

A[0][0]

A[0][1]

A[1][0]

A[1][1]

A[2][0]

A[2][1]

100
102
104
106
A[0][0]
A[0][1]
A[1][0]
A[1][1]
st
nd

1 Row

2 Row

108
110
A[2][0]
A[2][1]

3rd Row

100
A
The address of the elements gets calculated by using the formula given below
A[i][j]= A+ i*size of the one dimensional array * size of the
data item + j * size of the data item
A[2][0]=100+2*2*2+0*2
=100+8+0= 108
Column major order
The given two dimensional arrays will get stored column by column.
For example consider the two dimensional array
Int a[3][2];
It is the collection of 3 one dimensional arrays and the capacity of each one
dimensional array is two.

100
A[0][0]

A[0][0]

A[0][1]

A[1][0]

A[1][1]

A[2][0]

A[2][1]

102
104
A[1][0]
A[2][0]
st
1 Column

106
A[0][1]

108
A[1][1]
nd
2 Column

110
A[2][1]

100
A

The address of the elements gets calculated by using the formula given below
A[i][j]= A+ j* number of one dimensional array * size of the
data item + i * size of the data item
A[2][0]=100+0*3*2+2*2
=100+0+4= 104
Applications:
BUBBLE SORT
This is the most commonly used sorting method. The bubble sort derives its
name from the fact that the smallest data item bubbles up to the top of the sorted array.
Principle : The bubble sort method compares the two adjacent elements starting from
the start of the list and swaps the two if they are out of order. This is continued up to the
last element in the list and after each pass, a check is made to determine whether any
interchanges were made during the pass. If no interchanges occurred, then the list must
be sorted and no further passes are required.
Algorithm:
ALGORITHM BUBBLESORT( K, N )
// K is the array containing the list of data items
// N is the number of data items in the list
FOR I=N-1 TO 1
Exch 0
Repeat For J = 0 to I-1
If K[J] > K[J+1]
Then
K[J] K[J+1]
Exch 1
End If
End Repeat
If (Exch = =0) Then
Exit Loop
End If
End FOR
End BUBBLESORT
In Bubble sort algorithm, initially Exch flag is assumed 0 because no exchange
was made initially. Starting from the first element, the adjacent elements in the list are
compared. If they are found out of order then they are swapped immediately and Exch
flag is set to 1. This comparison is continued until the last two elements are compared.
After this pass, the Exch flag is checked to determine whether any exchange has taken
place. If no exchange has taken place then the control comes out of the loop and the
procedure comes to an end as the list is sorted. If any exchange has taken place during
5

the pass, the I value is decremented by 1 and the next pass is continued. This process
continues till list is sorted.
Example:
N = 10 Number of elements in the list
Pass 1
Exch =0
j=0

j =1

j=2

j=3

j=4

j=5

j=6

j=7

j=8

j=9

42

23

74

11

65

58

94

36

99

87

Out of order Swap


23

42

74

exch=1

i=9

11

65

58

94

36

99

87

74

65

58

94

36

99

87

65

74

58

94

36

99

87

65

58

74

94

36

99

87

65

58

74

36

94

99

87

65

58

74

36

94

87

99

Out of order Swap


23

42

11

Out of order Swap


23

42

11

Out of order Swap


23

42

11

Out of order Swap


23

42

11

Out of order Swap


Pass 2
23

42

11

Out of order Swap


23

11

42

i=8
65

58

74

36

94

Out of order Swap


23

11

42

11

42

99

i=8
58

65

74

36

94

Out of order Swap


23

87

87

99

i=8
58

65

36

74

94

87

99
6

Out of order Swap

i=8

Pass 3
23

11

42

58

65

36

74

Out of order Swap


23

11

42

87

94

99

94

99

87

94

99

87

94

99

87

94

99

i=7
58

65

36

74

Out of order Swap

87
i=7

Pass 4
23

11

42

58

36

65

Out of order Swap


11

23

42

74
i=6

58

36

65

Out of order Swap

74
i=6

Pass 5
11

23

42

36

58

Out of order Swap

65

74

i=5

Pass 6
Adjacent numbers are compared up to i=4. But no swapping takes place. As there was no
swapping taken place in this pass, the procedure comes to an end and we get a sorted list:
11

23

36

42

58

65

74

87

94

99

Program:
#include <stdio.h>
#include <conio.h>
int K[10],N=10;
bubblesort(){
int i,j,exch=0,temp;
for(i=n-1;i>=1;i--){
exch=0;
for(j=0;j<=i-1;j++){
if(K[j]>k[j+1]){
temp=K[j];
K[j]=K[j+1];
K[j+1]=temp;
Exch=1;
7

}
}
if (exch==0)
break;
}
}
main(){
int i;
printf(\nEnter the values);
for(i=0;i<N;i++)
scanf(%d,&k[i]);
bubblesort();
printf(\nThe sorted values are);
for(i=0;i<N;i++)
printf( %d,k[i]);
}
The bubblesort( ) function sorts the data items in the array in the ascending order.
A variable i is declared to point to the number of elements under consideration in every
pass. The first two adjacent elements are compared and if they are found out of order
they are swapped else next two adjacent elements are compared. This process repeats till
the last two elements in the list. A variable exch is initially set as 0 and is used as flag to
determine whether an exchange has taken place. If exchange is done then the exch flag is
assigned 1. After every pass exch flag is checked. If it is 0, then control returns back to
the main function, else last pointer i.e, I is decremented once and next pass is continued.
In each pass the greatest elements in the list is pushed to the last position and the smaller
elements bubble up or move up.
In the main( ) function, the list of elements to be sorted will be received from the
user and stored in the array K. The list of sorted elements is displayed after invoking the
bubblesort function to sort all the elements in the ascending order.
Advantages:
1. Simple and works well for list with less number of elements.
Disadvantages:
1. Inefficient when the list has large number of elements.
2. Requires more number of exchanges for every pass.

LINEAR LIST
Linear List: A Linear list is a data object whose instances are of the form ( e 1, e2, en),
where n is a finite natural number.
ei Element of the list.
n length of the list.
s size of the element.
8

For example a list of names, list of marks, etc.


The operations that are performed on a linear list are,
1.
2.
3.
4.
5.
6.
7.
8.
9.

Create a list.
Delete a list.
Determine whether the list is empty.
Determine the length of the list.
Find the kth element.
Search for a given element.
Delete the kth element
Insert a new element.
Display all elements.

Abstract Data Type (ADT): An Abstract Data Type is a representation in which we


provide a specification of the instances as well as of the operations that are to be
performed. More precisely,
An Abstract Data Type is a data type that is organized in such a way that the
specification of the object and the specification of the operation on the object are
separated from the representation of the object and the implementation of the operation.
Hence an Abstract Data Type representation separates the implementation of the
operations from their specification, thus leading the way to object oriented programming.
Formula Based Representation:
In this method we use an array to represent the instances of an object. Each
position of array is called a cell or a node. Individual elements of an instance are located
in the array using a mathematical formula as shown.
Location (i) = i - 1 ith element is in position i-1 (if array starts with position zero)
(or)
Location (i) = i ith element is in position i (if array starts with position one)
A Linear list may be specified as an abstract data type (ADT) in which we provide a
specification of the instances as well as of the operations that are to be performed.
AbstractDataType LinearList
{
instances
ordered finite collection of zero or more elements
operations
Create( ): Create an empty linear list.
Destroy( ): Erase the list.
IsEmpty( ): Return true if the list is empty, false otherwise.
Length( ): Return the list size.
Find(k, x): Return kth element of the list in x and return false if not found.
9

Search(x): Return the position of x in the list otherwise return -1 if not found.
Delete(k): Delete the kth element.
Insert(k, x): Insert x just after kth element
Display( ): Display all elements of the list
}

LINKED LIST
Linked List: A Linked list is a collection of elements called nodes, each of which stores
two items called info and link. Info is an element of the list and a link is a pointer to the
next element. The linked list is also called a chain.
The different types of Linked lists are,
1. Singly linked list.
2. Doubly linked list
3. Circular linked list

SINGLY LINKED LIST


Singly Linked List: A singly linked list is a linked list in which each node contains only
one link pointing to the next node in the list.

In a singly linked list, the first node always pointed by a pointer called HEAD. If the link
of the node points to NULL, then that indicates the end of the list.
Operations on a singly linked list are,
1.
2.
3.
4.
5.
6.
7.

Count the number of elements.


Add an element at the beginning of the list.
Add an element at the end of the list.
Insert an element at the specified position in the list.
Delete an element from the list.
Search x in the list.
Display all the elements of the list.

10

The Abstract Data Type of the linked list may be written as shown.
AbstractDataType LinkedList
{
instances
finite collection of zero or more elements linked by pointers
operations
Count(HEAD ): Count the number of elements in the list.
Addatbeg(HEAD,x): Add x to the beginning of the list.
Addatend(HEAD,x): Add x at the end of the list.
Insert(HEAD,k, x): Insert x just after kth element.
Delete(HEAD,X): Delete the node which has the information X.
Search(HEAD,x): searches X in the list if found displays the element found if not
Found it displays the element not found
Display(HEAD ): Display all elements of the list
}
Algorithm:
Count:
The first operation count( ) counts the number of elements in the list. Let Head be
a pointer pointing to the beginning of the list. If the head points to NULL, then the list is
empty. In the count algorithm given below, we first create a temporary pointer Temp and
make it point to the node where Head is pointing. Since Head always points to the
beginning of the list, Temp is now pointing to the first node in the list. A counter is
initialized to zero. The list is traversed using a while loop and every time we move to the
next node, the counter is incremented. If Temp doesnt point to NULL, that means the
end of the list is not reached and hence temp is made to point to the next node. This is
repeated till the end of the list and finally we have the number of elements of the list in
the count variable.
ALGORITHM COUNT(HEAD)
BEGIN
Temp Head
Count 0
While Temp NULL
Count Count +1
Temp Link (Temp)
End While
Write (Count)
End COUNT

11

Addatbeg:
The operation Addatbeg, adds the element k at the beginning of the existing list.
First a temporary pointer is created and made to point to the node where head is pointing.
The given element K is stored in a new node. Check if the list is empty. If so make link
of new node point to NULL and make Head to point to new, making it the first element of
the list. If the list is not empty, then the link of new is made to point to the first element
of the existing list and Head is made to point to the new node.

12

ALGORITHM ADDATBEG(HEAD, K )
BEGIN
Info(New) K
If (Head = NULL)
Then
Link(New) NULL
Else
Link(New) Head
Endif
Head New
End ADDATBEG
Addatend:
The operation Addatend, adds the given element k at the end of the existing list.
Initially it is checked whether the list is empty or not. If the list is empty then create a
new node New and add the value k to the info part of the node. The link part is made to
point to NULL. Then the Head is made to point this new node making it the first node.
If the list already has some nodes and now a new node is to be added to the end of the
list, then create a temporary pointer called Temp and make it to point to the Head initially.
Then move the pointer the last node and now create a new node with value x. Make the
link part point to NULL. Now the link of temp is made to point to the new node, thus
making the new node as the last node of the list.

13

ALGORITHM ADDATEND(HEAD, K )
BEGIN
If (Head = NULL)Then
Info(Temp) k
Link(Temp) NULL
Head Temp
Else
Temp Head
While link(Temp) NULL
Temp link(Temp)
End While
Info(New) k
Link(New) NULL
Link(Temp) New
Endif
End ADDATEND( )
Insert at k:
The operation Insertatk( k, x ) inserts the given element x in the k th position. A
temporary pointer Temp is created and made to point to Head. Now the Temp pointer is
moved to the k 1 th node. A new node with value x is created and the link of the new
node is made to point to the position where the link of temp is pointing. Then the link of
temp is made to point to the new node. Thus the given element is inserted in the position
k.

14

ALGORITHM INSERTATK(HEAD, K, X )
BEGIN
Temp Head
I 1
While I < k-1
Temp link(Temp)
I I+1
End While
Info(New) x
Link(New) Link(Temp)
Link(Temp) New
End INSERT( )
Delete ( x )
The operation Delete( x ), deletes the node with value x. The given value x is
compared with each node starting from the first node and continued till the last node. If
the node to be deleted is the first node, then simply Temp pointer is made to point to
Head and then Head is safely moved to point the next node. Now the first node is deleted
by deleting the Temp. If the node to be deleted is not the first node, then make it the old
node and move the temp pointer to the next node. Check if that is the node to be deleted.
If so, make the link of old point to link of temp and delete the node pointed by temp.
15

Now the node pointed by temp can be deleted. If this is also not the node to be deleted
then make this old node and move the Temp pointer to the next node and the process is
repeated till we reach the last node or the specified node is deleted.
ALGORITHM DELETE( HEAD,X)
BEGIN
Temp Head
While Temp NULL
If (Info(Temp) =X)Then
If (Temp = Head) Then
Head link(Temp)
QUIT
Else
Link(old) Link(Temp)
QUIT
End If
Else
Old Temp
Temp Link(Temp)
End If
End While
End DELETE( )

16

Search:
The operation Search( x ), searches the given value x in the list. If found it
displays the element found message. A temporary pointer Temp is created and made to
point to the Head. Now info part of Temp is compared with the value x. If the value
matches the node the appropriate message will be displayed to the user otherwise Temp
pointer is moved to the next node. This is repeated till the end of the list is reached or till
the element to be searched is found.

17

ALGORITHM SEARCH(HEAD,X)
Begin
Temp Head
While Temp NULL
If (Info(Temp) = X)Then
Write(Element found)
Quit
Else
Temp Link(Temp)
End While
End SEARCH( )
Display:
The operation Display( ), displays all the value in each node of the list. A
temporary pointer is created and made to point to Head initially. Now info part of Temp
is printed and Temp is moved to the next node. This is repeated till the end of the list is
reached.
ALGORITHM DISPLAY( HEAD )
Begin
Temp Head
While Temp NULL
Write(INFO(Temp))
TempLink(temp)
End While
End DISPLAY( )
Program
//Linked Lists and various operations on it
#include <iostream.h>
#include <conio.h>
class linklist
{
private:
struct node
{
int data;
node *link;
}*p;
public:
linklist();
void addatend(int num);
void addatbeg(int num);
void insert(int loc, int num);
int count();
18

void del(int num);


void search(int num);
void display();
~linklist();
};
linklist::linklist()
{
p=NULL;
}
void linklist::addatend(int num)
{
node *temp, *r;
if (p==NULL)
{
temp=new node;
temp->data=num;
temp->link=NULL;
p=temp;
}
else
{
temp=p;
while (temp->link!=NULL)
temp=temp->link;
r=new node;
r->data=num;
r->link=NULL;
temp->link=r;
}
}
void linklist::display()
{
node *temp;
temp=p;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->link;
}
}
linklist::~linklist()
{
node *temp;
while (p!=NULL)
{
temp=p->link;
19

delete p;
p=temp;
}
}
void linklist::addatbeg(int num)
{
node *temp;
temp=new node;
temp->data=num;
temp->link=p;
p=temp;
}
void linklist::insert(int loc, int num)
{
node *temp, *r;
int i=1;
temp=p;
while (i<loc-1)
{
temp=temp->link;
if (temp==NULL)
{
cout<<"\nThere are less than "<<loc<<" elements in list"<<endl;
return;
}
i++;
}
r=new node;
r->data=num;
r->link=temp->link;
temp->link=r;
}
void linklist::del(int num)
{
node *old, *temp;
temp=p;
while (temp!=NULL)
{
if (temp->data==num)
{
if (temp==p)
p=temp->link;
else
old->link=temp->link;
delete temp;
return;
20

}
else
{
old=temp;
temp=temp->link;
}
}
cout<<"\n\nElement "<<num<<" not found";
}
void linklist::search(int num)
{
node *temp;
int count=1;
temp=p;
while (temp!=NULL)
{
if (temp->data==num)
{
cout<<"\nNumber found in position "<<count;
return;
}
else
{
temp=temp->link;
count++;
}
}
cout<<"\nNumber not found";
}
int linklist::count()
{
node *temp;
temp=p;
int c=0;
while (temp!=NULL)
{
temp=temp->link;
c++;
}
return c;
}

void main()
{
linklist l;
clrscr();
21

l.addatend(100);
l.addatend(200);
l.addatend(300);
l.display();
cout<<endl;
l.addatend(500);
l.display();
cout<<endl;
l.addatbeg(50);
l.display();
cout<<endl;
l.insert(4,1000);
l.display();
cout<<endl;
l.insert(10,2000);
l.display();
cout<<endl;
cout<<l.count();
cout<<endl;
l.del(300);
l.display();
cout<<endl;
cout<<l.count();
l.del(35);
l.search(1000);
l.search(300);
getch();
}
Output
100 200 300
100 200 300 500
50 100 200 300 500
50 100 200 1000 300 500
There are less than 10 elements in list
50 100 200 1000 300 500
6
50 100 200 1000 500
5
Element 35 not found
Number found in position 4
Number not found

22

DOUBLY LINKED LIST


Doubly linked list: The Doubly linked list is a collection of nodes each of which consists
of three parts namely the data part, prev pointer and the next pointer. The data part
stores the value of the element, the prev pointer has the address of the previous node and
the next pointer has the value of the next node.

In a doubly linked list, the head always points to the first node. The prev pointer
of the first node points to NULL and the next pointer of the last node points to NULL.
Operations on a Doubly linked list are,
1. Count the number of elements.
2. Add an element at the beginning of the list.
3. Add an element at the end of the list.
4. Insert an element at the specified position in the list.
5. Delete an element from the list.
6. Display all the elements of the list.
The Abstract Data Type of the linked list may be written as shown.
AbstractDataType DoublyLinkedList
{
instances
finite collection of zero or more elements linked by two pointers, one pointing the
previous node and the other pointing to the next node.
operations
Count(head ): Count the number of elements in the list.
Addatbeg(head,x): Add x to the beginning of the list.
Addatend(head,x):
Add x at the end of the list.
Insert(head,k, x): Insert x just after kth element.
Delete(head,x): Delete the element x from the list.
Search(head, x): searches the element x in the given list if found it displays the
element found message else element not found message will be displayed
Display(head ): Display all elements of the list
}
Algorithm:
The operations count( ), Search(x) and Delete(x) are similar to that of the singly
linked list.
Addatbeg:
23

The operation Addatbeg() adds a given element x at the beginning of the list. A
new node R is created and the value x is store in the data part of R. The prev pointer of R
is made to point to NULL and the next pointer is made to point to head. Then the prev
pointer of head is made to point to R and head is now moved to point to R making it the
first node. Thus the new node is added at the beginning of the doubly linked list.
ALGORITHM ADDATBEG(HEAD,X)
BEGIN
Info(R) x
Prev(R) NULL
Next(R) head
Prev(head) R
Head R
End ADDATBEG( )

Addatend:
The Addatend(x) operation adds the given element x at the end of the doubly
linked list. If the given list is empty then create a new node R and store the value of x in
the data part of R. Now make the prev pointer and the next pointer of R point to NULL.
Then head is pointed to R. If the list already contains some elements then, a temporary
pointer is created and made to point to head. The temp pointer is now moved to the last
node and then a new node R is created. The value x is stored in the data part of R and
next pointer of R is made to point to NULL. The prev pointer of R is made to point to
24

temp and next pointer of Temp is made to point to R. Thus the new node is added at the
end of the doubly linked list.
ALGORITHM ADDATEND(HEAD,X)
BEGIN
If (head = NULL) Then
Info(R) x
Next(R) NULL
Prev(R) NULL
Head R
Else
Temp head
While next(temp) NULL
Temp next(temp)
End While
Info(R) x
Next(R) NULL
Prev(R) Temp
Next(Temp) R
End If
End ADDATEND( )

25

Insert at K:
The Insertatk() operation inserts a given element x at the specified position k. A
temporary pointer is created and made to point to head. Then it is moved to the k-1 th
node. Now a new node R is created and the data part is stored with value of x. The next
pointer of R is made to point to next(temp) and the prev pointer of next(temp) is made to
point to R. Thus the links on the right side of the new node is established. Now the next
of Temp is made to point to R and the prev pointer of R is made to point to temp thus
establishing the links on the left side of the new node. Now the new node is inserted at
the position k.

ALGORITHM INSERTATK(HEAD,X,K)
Begin
Temp head
I1
Info(R)X
While I < k -1
Temp next (temp)
II+1
End while
Next(R) Next(temp)
Prev(Next(Temp) R
26

Next(Temp) R
Prev(R) Temp
End INSERT( )
Delete:
The Delete(x) operation deletes the element x from the doubly linked list. A
temporary pointer is created and made to point to head. Now the data of temp is
compared with x and if it matches that is the node to be deleted otherwise move to the
next node and again compare. If the node to be deleted is first node, then
prev(next(temp)) is made to point to NULL and head is pointed to next(temp). The node
pointed by temp is deleted. When the node to be deleted is not the first node, then
next(prev(temp)) is made to point to next(temp) and prev(next(temp)) is made to point to
prev(temp). The node pointed by temp is deleted.

ALGORITHM DELETE(HEAD,X)
Begin
Temp head
While temp NULL
If x = info(temp)
Then
If head = temp
Then
Prev(next(temp) NULL
27

Head next(temp)
quit
Else
Prev(next(temp)) prev(temp)
Next(prev(temp)) next(temp)
quit
End if
Else
Temp = next(temp)
End if
End while
End DELETE( )

Program
//Doubly linked list and the various operations on it
#include <iostream.h>
#include <conio.h>
class dlink
{
private:
struct node
{
node *prev;
int data;
node *next;
};
node *head;
public:
dlink();
~dlink();
void addatbeg(int x);
void addatend(int x);
void insert(int x, int k);
void del(int x);
void display();
};
dlink::dlink()
{
head=NULL;
}
dlink::~dlink()
28

{
node *temp;
while (head!=NULL)
{
temp=head->next;
delete head;
head=temp;
}
}
void dlink::display()
{
node *temp;
temp=head;
while (temp!=NULL)
{
cout<<temp->data<<"\t";
temp=temp->next;
}
}
void dlink::addatbeg(int x)
{
node *r;
r=new node;
r->data=x;
r->prev=NULL;
r->next=head;
head=r;
}
void dlink::addatend(int x)
{
node *temp, *r;
temp=head;
while (temp->next!=NULL)
temp=temp->next;
r=new node;
r->data=x;
r->prev=temp;
r->next=NULL;
temp->next=r;
}
void dlink::insert(int x, int k)
{
node *temp, *r;
temp=head;
int i=1;
while (i<k-1)
29

temp=temp->next;
r=new node;
r->data=x;
r->next=temp->next;
temp->next->prev=r;
r->prev=temp;
temp->next=r;
}
void dlink::del(int x)
{
node *temp;
temp=head;
while (temp!=NULL)
{
if (temp->data==x)
{
if (head==temp)
{
temp->next->prev=NULL;
head=temp->next;
delete temp;
}
else
{
temp->prev->next=temp->next;
temp->next->prev=temp->prev;
delete temp;
}
}
else
temp=temp->next;
}
}
void main()
{
clrscr();
dlink d1;
d1.addatbeg(50);
d1.addatbeg(60);
d1.addatbeg(100);
d1.display();
d1.addatend(30);
cout<<endl;
d1.display();
d1.insert(25,2);
cout<<endl;
d1.display();
30

d1.del(60);
cout<<endl;
d1.display();
d1.del(100);
cout<<endl;
d1.display();
getch();
}
Output:
100
100
100
100
25

60
60
25
25
50

50
50
60
50
30

30
50
30

30

31

Vous aimerez peut-être aussi