You are on page 1of 116

Linked Lists

Stay Connect ed
FOUR
109
CHAPTER
U
nited we stand, divided we fall! This has been proved
umpteen numbers of times. More united and connected we
are, more is the flexibility and scalability. Same is true with
linked lists. Thi s is perhaps one data structur e that has been used at
more number of places in computing than you can count. But,
beware. they are not simple. But the flexibility and performance
they offer is worth the pain of learning them.
Data Structures Through C++
' Erase the past".
"Makea nillian",
...all lhrough C++'
}:
lOB IIL--,--- --=:==:..:.:::.:::<:::..:"-'-'-
I
JI
illl
CHAPTER
Data Structures Through C++
~ r = - - - - - - - - - = - - -
'Erase the past",
'Make amillion',
...all through C++"
FOUR
];
Linked Lists
Stay Connected
U
nited we stand, divided we fall! This has been proved
umpteen numbers of times. More united and connected we
are, more is the flexibility and scalability. Same is true with
linked lists. This is perhaps one data structure that has been used at
more number of places in computing than you can count. But,
beware, they are not simple. But the flexibility and performance
they offer is worth the pain of learning them.
109
Igure 4-1. Unkad fist.
Linked list is a very common data structure often used to store
similar data in memory. While the elements of an array occupy
contiguous memory locations, those of a linked list are not
constrained to be stored in adjacent locations. The individual
clements are stored "somewhere" in memory, rather like a family
dispersed, but still bound together. The order of the elements is
maintained by explicit links between them. For instance, the marks
obtained by different students can be stored in a linked list as
shown in Figure 4-1.
Node

N stands for NULL

400 500
Observe that the linked list is a oCelerTlents.
nodes, each of which stores two ' items of information-c-an element
lir the list anaa A link is a P9inter or an
licitly_!!!C! location of the node containing the successor -of the
llliLeiefl}ent; In Figure 4-1, the arrows represent the links. The data
part of each node consists of the marks obtained by a student and
the Uok part is a pointer to the next node. The NULL in the last
node indicates that this is the last node in the list.
hat Is A Linked List
Data Structures Through C+ +


For stori ng similar data in memory we can use either an array or il
linked Ii-st. Arrays are simple to ' understand and elements of <Ill
array are easily accessible. But arrays suffer from the following
Iirnitatiosns:
Arrays have a fixed dimension. Once the size of an array
decicded it cannot be increased or decreased during execution
For example, if we construct an array of 100 elements and then
try tal stuff more than 100 elements in it, our program may
crasbs. On the other hand, if we use only 10 elements then the
space for balance 90 elements goes waste.
- elements are always stored in contiguous memory
locatiions. At times it might so happen that enough contiguous
locatiions might not be available for the array that we are tryim-
to create. Even though the total space requirement of the array
can bee met through a combination of non-contiguous blocks 01'
mem-ory, we would still not be allowed to create the array.
- Opersations like insertion of a new element in an array or
deletLcn of an existing element from the array are pretty
tediouus, This is because during insertion or deletion cad
element after the specified position has to be shifted one
positi on to the right (in case of insertion) or one position to the
left (i - n case of deletion). Refer Chapter 2 for more details.
Ii st overcomes all these disadvantages. A linked list call
8!Qw and shri gk in size during its lifetime. In other words, there is
'CS no maxirr-ium size of a linked list. The second advantage of linked
lists is tt.at, as nodes (elements) are stored at different memory
locations it hardlx. .ha ens that w ho memo when
The third advantage is thai, unlike arrays, whi e msening
the of
required.
II add new node
temp =new node;
}
else
{
node "temp;
node "temp, "r;
/I if the list isempty, create first node
if ( p == NULL)
{
1/ go tolast node
temp =p;
while ( temp -> link !=NULL)
temp =temp -> link ;
1/ add node at the end
r =new node ;
r -> data =num ;
r ->link =NULL;
temp .>link =r ;
temp =new node;
temp ->data =num ;
temp -> link =NULL ;
p=NULL ;
1/ adds anew node atthe beginning ofthe linked list
void Iinklist :: addatbeg ( int num )
{
II adds anode at the end ofalinked list
voidlinklist :: append ( int num )
{
Chapter 4: Linked Lists
- - - - - - - - - - - ~ I ~
Data Structures Through C++
private :
#include <iostream.h>
intdata ;
node link ;
} "p ;
public :
There arc several operations that we can think of per forming on
linked lists. The following program shows how to build a linked
list by adding new nodes at the beginning, at the end or in the
middle of the linked list. It also contains a function display( )
which displays all the nodes present in the linked list and a
function dele ) which can delete any node in the linked list. Go
through the program carefully, a step at 'a lime.
linklist( ) ;
void append ( int num ) :
void addatbeg ( int num ) ;
void addafter ( int loc, int num ) ;
void display( ) ;
int count( ) ;
void del ( int num ) ;
-linklist( ) ;
/I structure containing adata part and link part
struct node
{
class linklist
{
~ I L - . . . - - ---=-__
/Iinitializes data member
Iinklist :: linklist( )
-};
Operations On Linked List
If if node tobe deleted isthe
/I first node inthe linked list
node "Iemp =p ;
int c=0;
if ( temp .> data =="num )
{
coul endl ;
1/ traverse the entire linked list
while ( temp !=NULL)
{
cout temp -> data ' ' ;
temp =temp ->link ;
temp =temp ->link;
c++ ;
return c ;
node sold, slemp;
/I traverse the entire linked list
while ( temp !=NULL)
{
temp =p;
while ( temp != NULL)
{
II counts the number of nodes present inthe linked list
int linklist :: count( )
{
1/ deletes the specified node from the linked list
void Iinklist :: del ( int num)
{
Data Structures Through C++
cout "\nThere are Jess Qlan cc Joe
"elements inlist" <<: endl ;
return ;
/I skip todesired portion
tor ( intj =0: i < loe ; i++ )
{
temp =temp .> link;
node Stemp. sf ;
temp =p;
/I if end oflinked list isencountered
if ( temp == NULL)
{
temp ->data =num ;
temp .> link =p;
p=temp ;
/I insert new node
r= new node;
r.> data =num ;
r .> link =temp ->link;
temp .> link =r ;
node sfemp =p;
1/ adds anew node after the specified number of nodes
void Iinklist :: addafter ( intloe, int num)
r
1ill1 - - . : . . : . . . . . . . . . : . : . . . . : : . . . . : . . : . . . : : . . . . ; : . . : . . : . : . . . . : . ~ , . _ _
}
/Idisplays the contents of the linked list
void linklist :: display( )
{
cout "\n\nElements inthe linked list after deletion: " ;
I.display( ) ;
cout "'nNo. of elements inthe linked list: I.count( ) ;
cout "\n\nElements inthe linked list after addition at given position: ;
I.display( ) ;
cout "\nNo. ofelements inthe linked list" I.count( ) ;
I.del (99);
I.del ( 1) ;
I.del( 10);
cout "\n\nElements inthe linked list after addition at the beginning: ;
I.display( ) ;
I.addafter ( 7, 0) ;
I.addafter ( 2, 1) ;
I.addafter ( 5, 99) ;
cout "\nElements inthe linked list: ;
I.display( ) ;
I.addatbeg ( 999 ) ;
I.addatbeg ( BBB) ;
I.addatbeg ( rn );
I.append ( 14) ;
I.append ( 30 ) ;
I.append ( 25 ) ;
I.append ( 42 ) :
I.append ( 17) ;
void main()
{ .
linklist I;
Data Structures Through C++
II go tothe next node
ternp > temp -> link;
II delete the intermediate nodes inthe linked list
else
old ->link =temp ->link ;
II free the memory occupied by the node
delete temp ;
return ;
If traverse the linked list till the last node isreached
else
{
II old points to the previous node
old =temp ;
if ( temp:::: p)
p:: temp ->link;
q =P->link;
delete p;
p=Q ;
cout "\n\nElement' num not found" ;
node -q;
while ( p!=NULL)
{
}
llDl
r
- - - - - ----=------=- - - - -
II deallocates memory
linklist :: -Iinklist( )
{
}
temp -> data =num ;
temp .> link =NULL:
Chapt er 4: Linked Lists
Lastly, p is made to point to this node, since the first node has
been added to the list and p must always point to the first node .
In the other case, when the linked list is not empty, the condition
if ( P== NULL)
would fail, since p is non-NULL. Now temp is made to point to
the first node in the list through the statement
temp =p;
Then using temp we have traversed through the entire linked list
using the statements
while ( temp ->link 1= NULL)
temp =temp -> link;
The position of the pointers before and after traversing the linked
list is shown in Figure 4-2.
Data Structures Through C++

'-------------------=---
Elements inthe linked list after addition at the beginning:
777 888 999 14 30 25 42 17
Elements inthe linked list after deletion:
777 888 999 14 30 25 42 17 0
No. of elements inthe linked list 9
Element 10not found
Output:
Elements inthe linked list:
14 30 25 42 17
Elements inthe linked list after addition at given position:
777 888 999 1 14 30 99 25 42 17 0
No. of elements inthelinked list 11
The append( ) function has to deal with two situations:
(a) The node is being added to an empty list.
(b) The node is being added at the end of an existing list.
In the first case, the condition
if ( P== NULL)
gets satisfied. Hence, space is allocated for the node using ncw
Data and the link pan of this node are set up using' the
statements
To begin with we have designed a class linklist, which contains a
structure to represent a node. The structure node contains a data
and a link part. The . p has .been declared as poin.ter to
',.;0 node . .We have used this pointer as pointer to the first n?de In the
y 0 ' \. hnked list. No matter how many nodes get added to the hnked Jist,
r p would continue to point to the first node in the list. When no
node has been added to the list, p has been set to NULL to indicate
that the list is empty.

500
I2S 1
500
1
400
I
30
1400'
100

200
temp
El
Figure 4-3. Connection of nodes.
Instead of showing the links to the next node we have shown the
addresses of the next node in the ljnk part of each node. .
understand this with the help of an example. Suppose jn a
list containing 4 nodes, temp is pointing at the first node. This IS
shown in Figure 4-3.
When we execute the statement
temp =temp -> link ;
the right hand side yields 100. This address is now stored in temp.
As a result, temp starts pointing to the node at address
100. In effect the statement has shifted temp so that It has started
pointing to the next node in the list.
Let us now understand the addatbeg( ) function. Suppose there are
already 5 nodes in the list and we wish ad.d a ?ew. node at
beginning of this existing linked list. This situation IS shown In
Figure 4-4.
r
Data Structures Through C++ 120 111.- -.:::.-_
Figure 4-2. Working of append() function.
P temp
node being
added
Every time through the loop the statement temp = temp -> link
makes temp point to the next node in the list. When temp reaches
the last node the condition temp -> link !=' NULL would fail.
Once outside the loop we allocate space for the new node through
the statement
r =new node ;
Once the space has been allocated for the new node its data part is
stuffed with Dum and the link part with NULL. Note that this
node is now going to be the last node in the list.
All that now remains to be done is connecting the previous last
node with the new last node. The previous last node is being
pointed to by temp and the new last node is being pointed to by r .
They are connected through the statement
ternp-> link =r ;
this link gets established.
There is often confusion as to how the statement temp = temp _>
link makes temp point to the next node in the list. Let us
Chapter 4: Linked Lists
r -> link =temp -> link;
temp -> link =r;
(a) Before Insertion
temp
r
Ekl
(b) After Insertion
The first statement makes link part of node containing 99 to point
to the node containing 25. The second ensures. the
link part of node containing 30 points to the contammg 99.
On execution of the second statement the earher link between 30
Figure 45. Working of addafter() function.
All that remains to be done is readjustment of links such that 99
should go in between 30 and 25. This is achieved through the
statements

Data Structures Through C++
!EJI'--
Figure 4-4. Working of addatbeg() function.
After Addition
To begin with, through a loop we skip the desired number of nodes
after which a new node is to be added. Suppose we wish to add a
new node containing data as 99 after the 3
rd
node in the list. The
position of pointers once the control reaches outside the for loop is
shown in Figure 4-5(a). Now space is allocated for the node to be
inserted and 99 is stored in the data part of it.
For adding a new node at the beginning, firstly space is allocated
for this node and data is stored in it through the statement
. temp -> data =num ;
Now we need to make the link part of this node point to the
existing first node. This has been achieved through the statement
temp .>link =p ;
Lastly, this new node must be made the first node in the list. This
has been attained through the statement
p=temp;
The addafter( ) function permits us to add a new node after a
specified number of node in the linked list.
Linked list of floats
I Ashok B-1 Rajan B-1 Vljay SanJay 0
Linked list of names
Linked list of Structures I Records
The last step that remains is to deallocate memory. We have
written the code to deallocate memory in the destructor
-lioklist(). In this function we have traversed entire list a
loop. While doing so we have stored the address of next node 10 q
and called delete operator to deallocate memory to which p
pointing. Then we have reinitialised p with q and the process 1S
continued till p doesn't become NULL.
A common and a wrong impression that beginners carry is that a
linked list is used only for storing integers . However, a linked list
can virtually be used for storing any similar data. For example,
there can exist a linked list of floats, a linked list of names, or even
a linked list of records, where each record contains name, age and
salary of an employee. These linked lists are shown in Figure 4-7.
Figure 4-7. Different types of linked list .
This node
gets deleted
Data Structures Through C++
temp
node to be deleted - 99
Before Deletion
old
After Deletion
p


and 25 is severed. So now 30 no longer points to 25, it points to
99.
The dispJay( ) and couot( ) functions are straight forward. We
leave them for you to understand.
In deJ( ) function through the While loop, we have traversed
through the entire linked list, checking at each node, whether it is
the node to be deleted. If so, we have checked if the node being
deleted is the first node in the linked list. If it is so, we have simply
shifted p to the next node and then deleted the earlier node. .
If the node to be deleted is an intermediate node, then the position
of various pointers and links before and after the deletion is shown
in Figure
Figure 4-6. Worlcing of delete() function.
#include <iostream.h>
r ->link =temp ->link ;
temp .>link =r ;
return ;
}
/Igotothe next node
temp =temp ->link;
if (temp-> data <= num && (temp ->link -> data>num 1/
temp -> link ==NULL ))
}
p=r :
p->link =temp;
/I traverse the entire linked list tosearch the position
/I toinsert the new node
while ( temp != NULL)
{
}
else
{
node "temp =p;
r = new node;
r-> data =num:
node or , "temp =p;
1/ if list isempty orif new node istobe
/Iinserted before the first node
if ( p==NULL II P->data>num )
{
/Idisplays the contents ofthe linked list
void linklist :: display( )
{
}
void linklist :: add ( int num )
{
Data Structures Through C++
p=NULL ;
/26 II'-- __=__
private:
linklist( ) ;
void add ( int num ) ;
void display( ) ;
intcount( ) ;
void del ( int num ) ;
-linklist( ) ;
intdata ;
node -link;
}"p :
/Istructure containing adata part and link part
slruct node
{
public :
Now that we have understood how a linked list can be maintained
how about ensuring that every element added to the linked list gets
inserted at such a place that the linked list is always maintained in
ascending order? Here it is...
};
/Iadds node to an ascending order linked list
class linklist
{
/I initializes data member
linklist :: linklist( )
{
}
As.cending Order Linked List
~ I r - - - - - - - - : : - - - : : - - _
cout endI ;
II traverse the entire linked list
while ( temp != NULL)
{
cout temp -> data " " .
temp =temp _:':> link; I
}
~ I ~ u n ~ s the numberof nodes present inthe linked list
Int linklist :: count( )
{
node "temp =p ;
intc =0;
II traverse the entire linked list
while ( temp !== NULL )
{
temp =temp -> link;
CH;
}
return c ;
}
/I deallocate memory
linklist .: -linklist( }
{
node 'q ;
while (p 1= NULL)
{
q=p-> link;
delete p;
p= q;
}
void main()
Iinklist I;
I.add ( 5) ;
I.add ( 1);
I.add (6);
I.add ( 4) ;
I.add (7) ;
cout "\nElements inthe linked list: " ;
l.display( );
cout "\nNo. of elements inlinked list: " I.count( ) ;
Output:
Elements inthe linked list:
1 4 5 6 7
No. of elements inlinked list: 5
Let us now try to understand the function add( ) that is responsible
for maintaining the linked list in ascending order. The pointer p
holds either the address of the first node of the linked list, or a
NULL value in case of empty linked list. The add( ) function
lakes one parameter Dum that holds the data that is to be inserted
in the list.
Initially memory is allocated for the new node, its address is stored
in pointer r and using r the value of Dum is stored in its data part.
Now we need to establish the links. There are four different places
in the list , where the new node can be added depending upon,
which value it contains, they are as follows :
(a) To the empty list
(b) Before the first node in the list
(c) At the end of an existing list
New node
Before Addition
After Addition
r temp p
~
Case (b): Non-empty linked list, Addition at beginning
r p
c k J ~
Initially the pointer temp points to the first node and each time
through the while loop it is made to point to the next node in the
list. This is done through the statement
temp =temp ->link ;
Inside the while loop, num is compared with the data part of the
current node (node pointed to by temp) and the data part of the
next node (node pointed to by temp -> link). The new node should
be inserted if temp -> data is smaller than or equal to the num and
less than temp -> link -> data or if the current node is the last
node (i.e. temp -> link = NULL).
If both the conditions are false then we need to search the position
where the new node must be inserted such that the list is
maintained in the ascending order. For this, we need to traverse the
list and this is done through a while loop.
Case (c) and (d):
Figure 4-8(b) . Before the first node in the list .
Data Structures Through C++
Case (a): Empty Linked List
p =NULL r
~
p
dG
Befo Addition
New node
Case (a) and (b):
(d) In the middle of the list
All these four eases are discussed below.
~ I ....::....:....::..:..:..:.:..:....:..::.;....:..:.::..::....::....:...:....-
After Addition
A condition is checked through the statement
if ( P== NULL II P-> data> num)
This is done to check whether the list is empty or whether the new
node to be added is the first node. In either case p is made to point
to the new node. This is done through the statement
p=r ;
The value of temp is stored in the link part of the new node .
Pointer temp holds a value NULL if the list is empty and holds the
address of the first node if the new node that is to be added is'
added before the first node.
Figure 4-8(a). To the empty list.
Aft r AdcUtion
Before Addition
New node
After Addition
New node
ptemp
Cas (d): Non-empty linked list, Addition in middle
p
~ [ 2 ]
r
~
Having had a feel of linked list let us explore what further
operations can be performed on a linked list. How about reversing
the links in the existing linked list such that the last node becomes
Reversing The Links
Figure 4-8(d). In the middle of the list.
Chapler 4: linked Lists
Data Structures Through C++
Bafor Addition
p t mp r
~ ~
New node
Case (e): Non-empty linked list, Addition at end
p temp r
~ ~
132 11--------=---=------
Figure W(e). At rheend of an existing list.
#include <iostream.h>
node "temp ;
}
cout endl ;
1/ traverse the entire linked list
while ( temp !:; NUll)
{
cout temp .> data . " ;
temp s temp ->link;
node "temp =p ;
r =q ;
q:; q-> link ;
r ->link:; s :
s =r :
1/ traverse the entire linked list
while ( q!=NULL) /
{
q:; p ;
r =NULL;
p=r ;
/Iadd new node
temp> new node;
temp ->data =num ;
temp -> link =p;
p=temp;
1/ displays the contents ofthe linked list
void linklist :: display()
{
1/ reverses the linked list
void Iinklist :: reverse( )
{
node "q, "r, "s;
Chapter 4: Linked Lists
Data Structures Through C++
p:; NULL ;
intdata ;
node "link;
} "p;
linklist( ) ;
void addatbeg ( intnum ) ;
void reverse( ) ;
void dJsplay( ) ;
Jnt count( ) ;
-IJnklist( ) ;
private ~
/I structure containing adata part and link part "'
struct node
{
public :
the first node and the first becomes the last? Here is a program that
shows how this reversal of links can be achieved.
class linklist
{
/I adds anew node atthe beginning of the linked list
void linklJst :: addatbeg ( int num )
{
/I initializes data member
linklist :: Iinklist( )
{
}
};
lBJIL -.:.... ~ __
the number ofnodes present in the linked list
Int Ilnklist :: count( )
{
l.reverse{ ) ;
cout "\n\nElements inthe linked listafter reversing: ;
I.display( ) ;
cout "\nNo. of elements inthe linked list: " I.count( ) ;
s:: r;
r= q;
r ->link =s ;
cout "\nElements inthe linked list before reversing: ;
I.display( ) ;
cout "\nNo. of elements inthe linked list: I.count( ) ;
I.addatbeg ( 3) :
I.addatbeg ( 23 ) ;
I.addatbeg ( 5) ;
To begin with, we need to store theNULL value in the link part of
the first node, which is done throughthe statements '
In the function reverse( ) to traverse the linked list a variable q of
the type struct node * is required. We have initialized q with p.
Soq alsostarts pointing to the first node.
Elements inthe linked list after reversing:
7 43 17 3 23 5
No. of elements inthe linked list: 6
Output:
Elements inthe linked list before reversing:
5 23 3 17 43 7
No, of elements inthe linked list: 6
Chapter 4: Linked Lists
Data Structures Through c++
node "temp =p ;
intc=0 ;
node"q;
}
return c ;
while ( p!=NULL)
{
q= P->link;
delete p:
p=q :
linkJistl;
II traverse the entire linked list
while ( temp !=NULL)
{
temp> temp ->link;
c++ ;
I. addatbeg ( 7 ) ;
I.addatbeg ( 43 ) ;
I.addatbeg ( 17 ) ;
void main()
{

II deallocates memory
linklist :: -linklist( )
{
Finally outside the while loop the statement p == r, is executed.
This ensures that the pointer p now starts pointing to the node,
which is the last node of the original list. This is shown in Figure
4-9.
Data Structures Through C++
BUI if we store a NULL value in the link part of the first node then
the address of the second node is lost. Hence before storing a
NULL value in the link part of the first node, q is made to point to
the second node through the statement
q=q->link;
During the second iteration of the while loop, r points to the first
node and q points to the second node. Now the link part of the
second node should point to the first node, which is done through
the same statements
r which is of the type struct node * is initialized to a NULL
value. Since r contains NULL, s would also contain NULL. Now
r is assigned q so that r also starts pointing to the first node.
Finally r -> link is assigned s so that r -> link becomes NULL,
which is nothing but the link part of the first node.
Since r points to the first node, s would also point to the first node.
Now r is assigned the value of q so that r now starts pointing to
the second node. Finally r -> link is assigned with s so that r ->
link starts pointing to the first node. But if we store the value of s
in the link part of second node, then the address of the third node
would be lost. Hence before storing the value of s in r -> link, q is
made to point to the third node through the statement
q =q->link;
While traversing the nodes through the while loop .each time q
starts pointing to the next node in the list and r starts pointing to
the previous node. As a result, when the while loop ends all the
links has been adjusted properly such that last node becomes the
first node and first node becomes the last node.
s =r :
r =q;
r> link=s ;
!EJIl-- . : : . . . . . . . . . . . . ~ _ _ = _ _ _ _
Finally outside the while loop the statement p = r, is executed.
This ensures that the pointer p now starts pointing to the node,
which is the last node of the original list. This is shown in Figure
4-9.
Data Structures Through C++
r which is of the type struct node * is initialized to a NULL
value. Since r contains NULL, s would also contain NULL. Now
r is assigned q so that r also starts pointing to the first node.
Finally r -> link is assigned s so that r -> link becomes NULL,
which is nothing but the link part of the first node.
Since r points to the first node, s would also point to the first node.
Now r is assigned the value of q so that r now starts pointing to
the second node. Finally r -> link is assigned with s so that r ->
link starts pointing to the first node. But if we store the value of s
in the link part of second node, then the address of the third node
would be lost. Hence before storing the value of s in r -> link, q is
made to point to the third node through the statement
q=q->link ;
While traversing the nodes through the while loop .each time q
starts pointing to the next node in the list and r starts pointing to
the previous node. As a result, when the while loop ends all the
links has been adjusted properly such that last node becomes the
first node and first node becomes the last node.
But if we store a NULL value in the link part of the first node then
the address of the second node is lost. Hence before storing a
NULL value in the link part of the first node, q is made to point to
the second node through the statement
q =q.> link;
During the second iteration of the while loop, r points to the first
node and q points to the second node. Now the link part of the
second node should point to the first node, which is done through
the same statements
s=r :
r =q;
r ->link =5 ;
~ I l . . . - - - - - - ' ~ _
p=NULL;
1/ initializes data member
linklist :: Iinklist( )
{
}
};
public :
intdata;
node "link;
} "p;
private:
linklist( ) ;
VOid add ( int num ) ;
void display( ) :
intcount( ) ;
void merge( linklist &11 r 1inklist &12 ) ;
-linklist( } ;
/I structure containing adata part and link part
struct node
{
class linklist
{
#include <iostream.h>
Suppose we have two linked lists and we wish to merge the two
lists into a third list. While carrying out this merging we wish to
ensure that those elements which are common to both the lists
occur only once in the third list. The program to achieve this is
given below. It is assumed that within a list all elements are
unique.
Chapter 4: Linked Lists
Merging Of Linked Lists
Data Structures Through C++
s =NUll
r =NUll
r
r
q
q =NUll s r

Figure 49. Reversing the finks.

node rz;
return c ;
II traverse the entire linked list
while ( temp != NULL)
{
cout temp ->data . . ;
temp =temp -> link;
node -temp:: p;
intc =0 ;
temp =temp -> link;
c++ .
,
node -temp =p;
cout endl ;
II traverse the entire linked list
while ( temp !=NULL)
{
/I merges two linked lists, restricting the common
/I elements tooccur only once inthe final list
void linklist :: merge ( linklist &11 , linklist&12 )
{
II counts the number of nodes present inthe linked list
intIinklist :: count( )
{
II displays the contents of the linked list
void linklist :: display( )
{
Data Structures Through C++
p=r ;
p-> link =temp;
if ( temp ->data <num && ( temp ->link ->data> num II
temp ->link == NULL ))
r ->link =temp ->link ;
temp -> link =r ;
return ;
r= new node;
r ->data =num ;
!!traverse the entire linked listtosearch
lithe position to insert the new node
while ( temp !=NULL)
{
node "r, -temp;
temp =p;
r -> link =NULL ;
temp ->link =r ;
IIgo to next node
temp =temp -> link ;
II if list isempty orif new node istobe
II inserted before the first node
if ( P== NULL II P->data> num )
{
}
else
{
II adds node to an ascending order linked list
void linklist :: add ( int num )
{
EDI
- - - - - - - - - - - - - - - . . , ; ~ . . : . . . . . . : . . . -
z->link =new node ;
z =z->link;
z->data =11 .p->data;
11.p =11 .p->link;
Z ->data =12.p ->data ;
11 .p= 11.p -> link ;
12.p=12.p-> link ;
q=P->link;
delete p ;
p =q ;
_ _ _ A
}
Z ->link =NULL ;
node *q ;
while ( p!=NULL)
{
Z ->link =new node;
z=z->link ;
z->data =12.p ->data ;
12.p=12.p .> link;
1/ if end of second listhas been reached
while ( 12.p!=NULL)
{
/I if end of first list has not been reached
while ( 11 .p != NULL)
{
1/ deanocates memory
linklist :: -linklist( )
{
- - - - - - - - - - - I ~
( 'hapter 4: Linked Lists Data Structures Through C++
}
else
{
if ( 12.p->data < 11 .p.>data)
{
z->data =12,p->data;
12.p=12.p->link;
p=new node ;
Z =p ;
Z.> link =new node;
z=Z->link ;
}
else
{
Z=NULL ;
}
else
{
if ( 11 .p->data == 12.p->data)
{
if ( 11.p ->data <12.p->data)
{
z->data =11 .p->data ;
11 .p=11.p ->link;
II if both lists are empty
if( 11 .p== NULL && 12.p == NULL)
return ;
II traverse both linked lists till the end.
II If end of anyone list isreached loop isterminated
while ( 11 .p!= NULL && 12.p!=NULL)
{
II if node being added inthe first node
if ( P== NULL)
{
~ I . . . . . : : . . . . : . . : . : . . : . . : . . : . . : . ~ ~ : . . . . . . . . : : . - -
cout "\nNo. ofelements inthe merged linked list: " 13,count( ) ;
Output:
Elements infirst linked list:
9 12 14 17 35 61 79
No. of elements inlinked list: 7
In this program, as usual, we begin by constructing a class that
contains a structure to accommodate the data and link, which
together represent a node . By calling the function add( )
repeatedly two linked lists 11 and 12 are built. Finally, the merge( )
function is called through object 13 to merge two lists into one.
The merged list:
9 12 14 17 24 35 36 59 61 64 79 87
No. of elements inthe merged linked list: 12
Elements insecond linked list:
12 17 24 36 59 64 87
No. of elements inlinked list: 7
While merging the two lists it is assumed that the lists themselves
are in ascending order. While building the two lists the add( )
function makes sure that when a node is added the clements in the
lists are maintained in ascending order.
The function merge( ) receives two parameters, both are
references to the object of linklist class . Before calling merge( ) 13
contains a NULL value.
First of all we check if both the lists that are to be merged, are
empty or not. If the lists are empty then the control simply returns
from the function. Otherwise, a loop is executed to traverse the
lists that are pointed to by Il.p and J2.p. If end of any of the list is
. reached then the loop is terminated.
Data Structures Through C++
11 .add (9) ;
11 .add(12);
/1.add ( 14) ;
11.add ( 17) ;
/1 .add (35) ;
l1.add ( 61 ) ;
11 .add (79);
c o u ~ "\nElements infirst linked list: " .
11 .d/splay( ) ; ,
cout "\nNo. ofelements inlinked Iist" 11.count();
linklist 12 :
12.add (12) ;
12.add ( 17) ;
12.add ( 24 ) ;
/2.add ( 36 ) ;
12.add ( 59 ) ;
12.add ( 64 ) ;
/2.add ( 87 ) ;
~ [ - - - - - ~ - ; : - - - - - -
cou.! "\nlnElements insecond linked list: .
12.dJsplay( ) ; ,
cout '\nNo. ofelements in linked list: " f2.count( ) ;
linklis! 13;
13.merge ( /1, J2 ) ;
cout "\n\nThe merged list" ;
J3.display( ) :
void main()
{
linklist 11 ;
q second
Figure 4-10. Merging of two linked lists.
z third

Pfirst
"-
If we reach end of first and/or second list the .while loop
terminates. If we have reached end of only one list the
remaining elements of the other list are simply .dumped In the
merged list as they are already in .ascendln
g
order. The
working of the merge function is shown In FIgure 4-10.
Chapter 4: Linked Lists

Data Structures Through C++
To begin with, a NULL value is stored in z, which is going to
point to the resultant merged list. Inside the while loop, we check
the special case of adding the first node to the merged list pointed
to by z. If the node being added is the first node then z is made to
point to the first node of the merged list through the statement
z=p;
Next, the data from both the lists are compared and whichever is
found to be smaller is stored in the ' data part of the first node of
the merged list. The pointers that point to the merged list and to
the list from where we copied the data are incremented
appropriately.
if( 11.p ->data == 12.p ->data)
{
z -> data =12.p ->data ;
11.p =11 .p ->link;
12.p =12.p -> link;
During the next iteration of the while loop the if condition for first
node fails and we reach the else block. Here we allocate the
memory .or the new node and its address is stored in z -> link.
Then z is made to point to this node, through the statement
Z =Z ->link;
While comparing the data, if we find that the data of both the lists
are equal then the data is added only once to the merged list and
pointers of 11 and U are incremented, this is done through the
statements
The procedure of comparing, adding the data to the merged list
and incrementing the pointer of the merged list and the list from
where the data is added is repeated till any of the list ends.
---=-__
z
first
first
Figure 4-10. Merging two linked lists (Contd.) .
Figure 4-10. Merging two linked lists (contd.).
Data Structures Through C++
p first
third z
~
150 I I ~ - - - - - - - - = - - - - - = - - - - -
Figure 4-10. Merging two linked lists (Contd.).
Figure 4-10. Merging two linked lists (Contd.).
q p
Before Exchange
p q
After Exchange
Suppose the elements 8 and 3 are to be exchanged. While
carrying out the exchange only 8 gets exchanged with 3. The
link part of node being pointed to by p and the link part of
node being pointed to by q remains unchanged. To make this
absolutely clear take a look at Figure 4-12. In this instead of
showing links we have shown the actual addresses of nodes.
Referring to Figure 4-12, you can observe that after the
exchange of 8 and 3 the addresses stored in nodes pointed to
by p and q (i.e. addresses 500 and 750) have remained intact.
Figure 4-11. Sorting the list by e x ~ h a n g i n g the data part of the node.
Data Structures Through C++
first
Figure 410. Merging two lists (Contd.) .
(a) Exchange the data part of two nodes, keeping the links intact.
This is shown in Figure 4-11.
Suppose, we wish to sort the elements of a linked list. We can use
any of the standard sorting algorithms for carrying out the sorting.
While performing the sorting, when it is time to exchange two
elements, we can adopt any of the following two strategies:
lEllL...-- ..:::.....-_
Sorting A Linked List
After Exchange
#include <iostream.h>
Instead of links if you look at actual physical addresses stored
in the link part you may get a clearer idea about how the links
are being readjusted. This is shown in Figure 4-14.
In this chapter we would implement both the methods to sort a
linked list. Here is a program for the first one.
Of the two methods suggested above, the first one is easier to
implement, but the second one is likely to be more efficient. This
is because if the data part contains an employee record (containing
name, age, salary etc.) then to carry out exchange of this record
would be inefficient time wise as well as space wise. Instead if we
adopt second method. since we are readjusting only the links this
would involve only pointers and not the bulky structures
representing records.
p
q
03
dE 03
dE EEl
200 440 500 600 750
Before Exchange
p
q

dE EEl
200 440
500 600 750
After Exchange
Figure 4-14. Adjustment of links for sorting the list.
q
Data Structures Through C++
p
Before Exchange
0J-CEE-Cfr?
p q
03 dB GEl
200 440 SOO 600 750
Before Exchange
p q
[B-

@G]
200 440 SOO 600 750
After ExchanQe
Figure 4-13. Adjustment of links for sorling the list.
FIgure 4-12. Sortmg by keeping the links intact .
(b) Keep the data in the nodes intact. Simply readjust the links
such that effectively the order of the nodes changes. This is
shown in Figure 4-13.
!Ell
/Istructure containing adata part and linkpart
struct node
{
cin val ;
append ( val) ;
cout "\nAny More Nodes (YIN): " :
cin ch:
} while ( ch == ''I II ch == 'Y' ) ;
1/ gotolast node
while ( temp ->link != NULL)
temp =temp ->link ;
node "temp;
temp =p ;
temp =new node ;
p=temp ;
II add node at the end
temp ->link =new node ;
temp =temp -> link ;
/I assign data tothe last node
temp ->data =num ;
temp -> link =NULL ;
II if the list isempty, create first node
if ( temp == NULL)
{
}
else
{
II adds a node at the end ofa linked list
voidlinklist :: append ( int num)
{
},
II displays the contents of the linked list
Data Structures Through C++
linklist( ) ;
void getdata( ) ;
void append ( int nurn ) ;
void display( ) ;
int count( ) ;
void selection_sort ( int num);
void bubble_sort ( int num ) ;
-Iinklist( ) ;
public :
do
{
intdata ;
node "link ;
} 'p ;
p=NULL ;
private:
cout "\nEnter a value:" ;
class Iinklist
{
~ I - - - - ~ . : . . . . . . : . . . . - -
} ;
/I initializesdata member
Iinklist :: Iinklist( )
{
II accepts data
void linklist :: getdata( )
{ .
intval;
charch ;
/Icounts the number of nodes present inthe linked list
intlinklist :: count{ )
{
for ( int j =i + 1; j < n; j++ )
{
if ( q-> data> r -> data)
{
temp =q->data ;
q.>data =r -> data ;
r -> data =temp;
}
q =q ->link ;
r =r -> link ;
if ( q -> data> r ->data)
{
temp =q->data;
q ->data =r .>data;
r .>data =temp;
for ( intj =1 ; j < k; j++ )
{
}
q=q-> link ;
q=p;
r =q.> link;
}
r =r -> link;
r =q->link ;
k =n;
for ( int i =0 ; i < n- 1 ; i++. k- )
{
int k, temp ;
node 'q, 'r ;
1/ sort list using bubble sort
void linklist :: bubble_sort ( int n)
{
Data Structures Through C++
II traverse the entire linked list
while ( temp != NULL)
{
temp =temp ->link:
c++ .
r
return c ;
cout endI ;
II traverse the entire linked list
while ( temp != NULL)
{
node 'temp =p;
q= p;
for ( int i =0; i <n- 1; i++ )
{
node 'temp =p ;
int c =0;
cout temp-> data ' ";
temp =temp -> link ;
void linklist :: display( )
{
~ I r - - - - - ~ - - - - - -
II sorts listusing selection sort
void linklist :: selection_sort ( int n)
{
inttemp;
node 'q, 'r ;
cout "\nEfements infirst linked listbefore sortinq:" ;
11 .dispJay( ) :
cout c in\nElemenls insecond linked list before sorting: " ;
12.display( ) ;
In the above program, we have added nodes to the linked list using
getdala( ), which in tum calls appeod( ). After accepting the data,
12.bubble_sort( n) ;
cout "\nElements insecond linked listafter bubble sorting: ;
12.display( ) ;
Elements infirst linked list before sorting:
29 7 99 3
Elements infirst linked list after selection sorting:
3 7 29 99
Output:
Enter a value: 29
Any More Nodes (YIN): Y
Enter a value: 7
Any More Nodes (YIN): Y
Enter avalue: 99
Any More Nodes (YIN): Y
Enter avalue: 3
Any More Nodes (YIN): N
Elements insecond linked list before sorting:
37 49 13 2
Elements insecond linked list after bubble sorting:
2 13 37 49
Enter avalue: 37
Any More Nodes (YIN): Y
Enter avalue: 49
Any More Nodes (YIN): Y
Enter avalue: 13
Any More Nodes (YIN): Y
Enter avalue: 2
Any More Nodes (YIN) : N
Data Structures Through C++
intn=11.count( ) ;
11 .selection_sort( n) ;
cout "\nElements infirst/inked list after selection sorting'" .
11.display() ; . I
linklist/1 I
11 .getdata( ) ;
node -q;
q=P->link;
delete p;
p=q :
while ( p!=NULL)
{
linklist /2 ;
12.getdata( ) ;
n=12.count( ) ;
~ [
' - - - - - - - - - = - : : . : . . : . : . . . . : . . : : . : . . . . : . . : . : : . = - = . . . . : . . . : . . : . : . ~ ~ : - - . : . . . -
II deallocates memory
linklist :: -linklist( )
{
void main()
{
Iinklist( ) ;
void getdata( ) ;
void append ( intnum ) ;
void display( ) ;
void selection_sort( ) ;
void bubble_sort( ) ;
#include <lostream.h>
public :
class linklist
{
private :
/I structure containing adata part and link part
struct node
{
temp.age :: p-> age;
p.> age :: q-> age ;
q.>age:: temp.age "
temp.sal :: P->sal;
p.> sal:: q-> sal ;
q.>sat>temp.sal ;
Thus a great deal of time would be lost in swapping the records,
if di st links instead of
This limitation can be overcome I we rea JU .
, d Thi has been achieved through the follOWing
exchangmg ata. IS .
program.
int data ;
node Iink ;
} "start ;
strcpy ( q->name, temp.name )
Data Structures Through C++ 162 IIL-.- ___=___
slruct emp
{
In the selection son logic instead of comparing anode' s value with
the values of all other nodes, the values of successive pairs of
nodes are compared. Once again if the pair of numbers being
compared are not found in order then the numbers are exchanged.
In the bubble son logic each node 's value is compared with other
nodes in turn. On comparison if the pair of numbers being
compared are not found to be in order then the contents of the two
nodes being compared are exchanged.
char name ;
int age;
float salary :
} temp ;
we have sorted the linked list using selectiou sortt ) function. The
same procedure of receiving data, building a linked list and sorting
is repeated again; the only difference being, this time we have used
the bubble_sort() function to earry out the sorting,
Both the functions suffer from the limitation that they swap the
data pan of the node. Consider a case where we have to son
records. In this case, to perform one exchange of records, we need
to copy the entire record thrice using the following statements:
strucl empl
{
char name;
int age ;
float salary ;
ernpl fink ;
} "p, "q ;
strcpy ( temp.name, p.> name) ;
strcpy ( p.>name, q-> name) ;
caul "lnAny More Nodes (YIN): ;
cn >ch ;
} while ( ch == 'y' II ch == 'Y' ) :
/I add node atthe end
temp -> link =new node ;
temp =temp -> link ;
node -temp =start ;
p=r =start ; .
while ( p->link !=NULL)
else
{
II go tolast node . .
while (temp -> link !=NULL)
temp =temp ->link ;
cout endl ;
II traverse the entire linked list
while ( temp != NULL)
{
cout temp ->data ' ';
temp =temp .> link;
II assign data tothe last node
temp. -> data =num ;
temp -> link =NULL ;
Chapt er 4: Linked Lists
/I sorts list using selection sort method
void linklist .: selection_sort( )
{
node -P. -q. -r, 's, -temp ;
If displays the contents of the linked list
void Iinklist :: display( )
{
- - - - - - - - - - - - I ~
Data Structures Through C++
-l inklist( ) ;
start =NULL ;
~ I , - - - - - - - - ~ -
};
temp =new node ;
start =temp ;
cout 'InEnter avalue: ;
dn val ;
node -temp ;
temp =start ;
II if the list isempty, create first node
if ( temp == NULL)
{
append ( val) ;
II initializes data member
linklist :: linklist( )
{
}
II accepts data
voidlinklist :: getdata( )
{
int val, n ;
char ch ;
do
{
/I adds anode at the end of alinked list
void linklist :: append ( int num )
{
P-> link =q-> link ;
q-> link =p;
P->link =q-> link;
q-> link =p ;
r -> link =q ;
s=q:
q=q -> link ;
start =p ;
temp =p ;
p= q ;
q =temp ;
temp =q.> link ;
q->link =p -> link ;
p->link =temp ;
s =q ;
q = q ->link ;
r ->link =q ;
s> link =p;
temp =p ;
p> q ;
q = temp ;
S -> link = p;
temp =q ->link ;
q->link =p-> link ;
p ->link=temp ;
}
else
{
-=q;
. if( p == start )
{
}
else
{
Chapt er 4: Linked Lists
- - - - - - - - - - - I ~
Data Structures Through C++
}
else
{
temp =p ;
p=q;
q=temp;
temp =p :
p=q;
q =temp ;
if ( P== start )
{
s =q ;
q=q->link ;
start =p ;
r =p ;
s=q ;
q=q->link;
if ( P-> link == q)
{
}
else
{
jf ( P->data>q->data)
{
s =q =P-> link ;
while ( q!= NUll)
{
~ I
~ - - - - - - - - - - - - - - - ~ ~ - -
II r precedes pand spoints to the node up to
II which comparisons are to be made
while ( s !=start -> link)
{
r -> link =q ;
r =q ;
P-> link:: temp ;
}
else
{
while ( start !=NULL)
{ .
q=start ->link ;
delete start ;
start =q ;
}
q=P-> link ;
if ( q== s )
s =p;
node 'q ;
r =p ;
p=P->link ;
linkJist 11 ;
cout -'nElements infirsllinked list before sorting: ;
11.getdata( ) ;
void main(}
{
/Ideallocates memory
Iinklist :: -linklist( )
{
Data Structures Through C++
if ( P-> data> q->data)
{
if ( P== start )
{
temp:: q-> link ;
q-> link =p;
P-> link =temp;
}
r =p;
p=P->link ;
r:: p=start ;
q:: p-> link ;
q:: q -> link ;
start =q ;
r= q ;
temp =q->link ;
q->link =p:
}
else
{
while ( p !:: s)
{
~ I - - = : . . = . : : . . . . : : . : . : . . . . : . = : : . : . . : : : . . . . : : ~ ~ ~
II sorts list using bubble sort method
voidIinklist :: bubble_sort( )
{
node -p, "q, 'r, 's, -temp;
s:: NULL ;
Data Structures Through C++
11.display( ) ;
11.selection_sort( ) ;
cout "\nElemenls infirsllinked list after selection sorting' " .
11 .display() ; . ,
Iinklisl12 ;
12.geldata( ) ;
cout "'n\nElements insecond linked list before sorting: " ;
12.display() ;
12.bubble_sort( ) ;
cout "I.nElemenls insecond linked list after bubble sorting' " ,
12.display( ) ; . ,
Output:
Enter avalue: 29
Any More Nodes (YIN): Y
Enter avalue: 7
Any More Nodes (YIN): Y
Enter avalue: 99
Any More Nodes (YIN): Y
Enler avalue: 3
Any More Nodes (YIN): N
Elements infirst linked list before sorting:
29 7 99 3
Elements infirsllinked list after selection sorting:
3 7 29 99
Enter avalue: 37
Any More Nodes (YIN): Y
Enter avalue: 49
Any More Nodes (YIN): Y
Enter avalue: 13
Any More Nodes (YIN): Y
Enter avalue: 2
Any More Nodes (YIN): N
Elements insecond linked list before sorting:
37 49 13 2
Elements insecond linked list after bubble sorting:
2 13 37 49
Unlike the previous program we have omined the countf )
function. Instead we have traversed the entire linked list while
carrying out the sorting.
Let us understand the selectton sortf ) and the bubble_sort( )
functions one by one. In selectiQD_sort( ), pointers p and q point
to the nodes being compared and the pointers rand s point to the
node prior to p and q respectively. Initially, p and r are set to
start, where start is a pointer to the first node in the list. Also, to
begin with q and s are set to p -> link. The outer loop is controlled
by the condition p -> link !== NULL and the inner loop is
controlled by the condition q !== NULL.
While adjusting the links of the nodes being compared, we would
encounter one of the following four cases:
(a) Nodes being compared are adjacent to one another and p is
pointing to the first node in the list.
(b) Nodes being compared are adjacent to one another and p is
not pointing to the first node.
(c) Nodes being compared are not adjacent to one another and p
is pointing to the first node.
(d) Nodes being compared are not adjacent to one another and p
is not pointing to the first node.
Let us now understand these cases one by one.
You can trace these operat ions with the help of following Figure 4-
15.
-,
' I
I I
, I
Chapter 4: Linked Lists
~ ~ ~
~ ~ ~
~ ~ ~
Figure 415. Selection sort: case (a).
Case (b):
When the nodes being compared are .adjacent and p is ~ o t pointing
to the first node, the following operations are performed.
P-> link=q -> link;
q ->link =p;
r> link =q ;
- - ~ - - - : - ; - : - - : - - - - - - - - I ~
Data Structures Through c++ :
EDl _
When the nodes being compared are adjacent and p is pointing to
the first node, the following operations are performed:
Case (a):
p.> link =q-> link ;
q ->link =p;
temp =p ;
p=q;
q =temp ;
start =p ;
r= p;
s =q;
q=q->link;
temp =p ;
p=q :
q =temp ;
You can trace these operations with the help of Figure 4-17.
s =q ;
q =q-> link ;
start =p ;
temp =q->link ;
q-> link=p->link :
p->link =temp ;
s -> link =p ;
When the nodes being compared are not adjacent and p is pointing
to the first node, the following operations are pcrfonned:
Case (c):
Data Structures Through C++
s r
You can trace these operations with the help of Figure 4-16.
temp =p:
p=q ;
q=temp ;
s =q;
q =q.> link;
Figure 4-16. Selection sort: case (b).
- - - - - - - - - - - I ~
VI 1\1 can trace these operations with the help of Figure 4-18.
" q :
II Q-> link ;
IlIlIlp =P;
It q ;
'\ temp ;
, link =q;
" -" Iink=p:
( "tUleter 4: Linked Lists
q
p
Data Structures Through C++
start P
r q
r s
Figure 4-17. Selection sort : case (c).
Case (d):
Lastly, when the nodes being compared are not adjacent and p is
not pointing to the first node, the following operations are
performed:
temp =q .> link;
q->link =p-> link ;
p->link =temp;
,.-
(a) Ifp is pointing to the first node
(b) Ifp is not point ing to the first node
In the first case , the assigmnents that are carried out are given
below:
temp:: q-> link ;
q-> link > p:
p-> link:: temp ;
You can trace through these assignments using Figure 4-19. .
Now while comparing the nodes there are only two cases to be
tackled. These are:
Now let us undersland the bubble_so
r t(
) function. In
bubble_sort( ) P and q point 10 the nodes being compared, r
points to the node prior to the one pointed to by p. Lastl y, s is used
to point to the node up to which we have to make the comparisons.
Initially, p and r are set 10 start, q is set to p -> link and s is set to
NULL. The outer loop is controlled by the condition s ! ~ start ->
link and the' imler loop is controlled by the condition p ! ~ s.
start :: q ;
r:: q:
These statements are simpl y moving sand q one node down the
list. Once the control comes out of the inner loop, we need to move
r and p one node down the list.
Chapter 4: Linked Lists
p
p
Data Structures Through C++ :
q
s
p
G:EJ
r
r
r
q=N
Figure 4-18. Selection sort: case (d).
If p .-> data is not greater than q -> data then the only changes
required are
s:: q:
q ::q-> link ;
E[l1r---------::::----:------
qs
qs
r q s
p
r
start
start r
During each iteration, of the outer loop, the biggest element gets
stored at the end. This element naturally should not be, used to
carry out the comparisons during the next iteration of the outer
loop. That is, during each iteration of the outer loop, the inner loop
should be executed one time less. The pointer s is used to keep
track of the node up to which the comparisons should be made
during the next iteration.
Figure 4-20. Bubble sort.
When the condition p->data > q->data becomes false, we need to
store the address of node currently being pointed to by p in rand
then shift p and q one node down the list.
Data Structures Through C++
q
start r q
s = NULL
s = NULL
Figure 419. Bubble Sort.
s =NULL
On the other hand, when p is not pointing to start, the following
operations should be performed:
temp =q ->link ;
q-> link =p;
P-> link=temp ;
r -> link =q ;
r=q;
Once again referring to Figure 4-20 would help you understand
these operations easily.
II structure containing adata part and link part
struct node
{
intdata;
node "link;
} 'front, "rear;
II if the queue isempty
if ( front :::: NULL)
front> q: z: 'i-.>
else
rear -> link:: q;
/I create new node
q:: new node:
q.> data> item;
linklist( ) ;
void addcirq ( intitem) ;
int delcirq( ) ;
void cirq_display( ) ;
-linklist{ ) ;
node'q;
front:: rear s NULL;
public:
II adds anew element atthe'end of queue
void linklist .: addcirq ( intitem)
{
/I initializes data member
Iinklist :: Iinklist( )
{
Chapter 4: Linked Lists

Data Structures Through C++ 182 II'-- __
private:
Circular Linked List
The linked lists that we have seen so far are often known as linear
linked lists. The elements of such a linked list can be accessed,
first by setting up a pointer pointing to the first node in the list and
then traversing the entire list using this pointer. Although a linear
linked list is a useful data structure, it has several shortcomings.
For example, given a pointer p to a node in a linear list, we cannot
reach any of the nodes that precede the node to which p is
pointing. This disadvantage can be overcome by making a small
change to the structure of a linear list such that the link field in the
last node contains a pointer back to the first node rather than a
NULL. Such a list is called a circular linked list and is illustrated
in Figure 4-21.
From any point in such a list it is possible to reach any other point
in the list. If we begin at a given node and traverse the entire list,
we ultimately end up at the starting point. A circular linked list
does not have a first or last node. We must, therefore, establish a
first and last node by convention. A circular linked list can be used
to represent a stack and a queue. The following program
implements a queue as a circular linked list.
Figure 4-21. Circular linked list.
#include <iostream.h>
class linklist
{
cout q -> data " . ;
q=q.> link; .
p=front ;
node 'q, 'p :
q =front ;
p> NULL;
}
delete rear;
linklist I ;
node"q;
while ( front !=rear)
{
q:: front ->link;
delete front;
front> q ;
Laddcirq ( 10 ) ;
I.addcirq ( 17 ) ;
l.addcirq ( 18) ;
I.addcirq ( 5) ;
I.addcirq ( 30 ) ;
cout endI ;
1/ traverse the entire linked list
while ( q!= P)
{
Chapter 4: Linked Lists
/I deallocates memory
linklist :: -l inklist( )
{
void main()
{
------------I@ Data Structures Through C++=
item =front-> data:
delete front ;
front =NULL ;
rear =NULL ;
}
else
{
}
return ( item) ;
node"q ;
int item:
II delete the node
q=front;
item =q->data ;
front =front ->link :
rear .>link =front;
delete q:
rear =q;
rear ->link =front ;
if ( front == rear)
{
1/ jf queue isempty
if ( front == NULL)
cout "'nqueue isempty" ;
else
{
}
return NULL ;
181
'-----------------...;:::",.,.--
II removes an element from front of queue
inllinklist :: delcirq( )
{
II displays whole of the queue
void linklist .: cirq_display( )
If the new node that is to be added is not the first node then the
address present in the link part of the last node is overwritten with
the address of the new node, which is done through the statement
rear -> link =q ;
Now the address of the new node IS stored in the pointer rear
through the statement
rear>q ;
and the address of the first node is stored in the link part of the
new node , This done through the statement
rear -> link =front;
Figure 4-22 shows how to add a new node in the circular queue
maintained as a linked list.
Now the statement
rear ->link =front ;
is executed which stores the address of the front node in the link
part of the rear node. This is done, because it is the property of a
circular linked list that the link part of the last node should contain
the address of the first node.
front =q;
After this the statement
rear =q;
is executed which stores the address of the new node into rear.
Thus both front and rear point to the same node.
Chapter 4: Linked List s
Data Structures Through C++

Output:
Elements inlinked list before deletion:
10 17 18 5 30 15
The pointers. front and rear point to the first node and the last
To begin with both the pointers front and rear
a:e initialized to NULL. The functions defined in the program are
discussed as follows:
co.ul , "\nElements inlinked list before deletion: " ;
I.clrq_dlsplay( ) : .
I.delcirq( ) ;
I.deldrq() ;
I.delcirq( ) :
Function addcirqt )
I.addcirq ( 15 ) :
cout "\nElements inlinked list after deletion' ,
I.cirq_display ( ) ; , ,
This function only one parameter item, which holds the
data that we wish to add to the queue While add]' d , . ' I ng a new no e
IS allocated for the new node whose address is stored in
pointer q. Then the data, which is present in item, is stored in the
data part of the new node.
Next a condit.ion is checked, whether the new node is being added
to an list. rf the list is empty then the address of the od .
stored In front. This is done through the statement nels
. Elements in linked listafter deletion:
5 30 15
New node
Figure 4-23 shows how the deletion of a node from the circular
queue maintained as a linked list happens.
If front and rear are pointing to different nodes then the address
of the first node is stored in a pointer q. Then the front pointer is
made to point to the next node in the list i.e. to the node, which is
pointed by front -> link. Now the address of the front is stored in
the link part of last node. Then the memory occupied by the node
being deleted is released.
For the non-empty list first it is checked whether front and rear
point to the same node or not. If they point to the same node then
the memory occupied by the node is released and front and rear
both are assigned a NULL value.
Function delcirq( )
In this function first a condition is checked whether the list is
empty or not. If thc list is empty then the control returns back to
calling function.
q
eb
Data Structures Through C++
Case I: Addition of node to empty list
New node
Before Addition
After Addition
Case II: Addition of node to non-empty list
front rear
~
Before Addition
front q fear
~
After Addition
front
!L
Lr!:fJ
front =rear =NULL q
eb
Figure 422. Addition of a node i n circular link list.
!Ell
- - - - - - - - - - - ~ ~ = . . . . . : : . . . : . . : . . : . . . . : ~ ~ ~
Data Structures Through C++
front rear
~
Before Deletion
front rear
After Deletion
front rear
~
Figure 4-23. Deletion of a node from circular link list.
Function cirq_display( )
~ n this function q is made to point to the first node in the list. This
IS ~ o n e because the entire list is traversed using q. Another pointer
~ IS s e ~ t ~ NULL initially. Then through the loop the circular
IInk.ed list IS traversed till the time we do not reach the first node
again. We would make the circle and reach the first node when q
equals p.
Chapt er 4: Linked Lists
First time through the loop p is assigned the address of the first
node after q has been moved to the next node. Had we done this
before the loop then the condition in the loop would have failed
the first time itself.
A Few More Operations
If you think carefully you can list out so many operations that can
be perfoml.ed on a linked Jist. For example, concaten'ating one
linked list at the end of another, deleting all nodes present in a
linked list, modifying certain elements in a linked list, etc. Given
below is a program for concatenation of linked list and erasing all
nodes in the list.
#include <iostream.h>
class linklist
{
private:
/I structure containing adata part and alink part
struct node
{
int data ;
node "link:
}.p ;
public:
linklist( ) ;
void append ( inl num ) :
void concat ( linklisl &1 ) ;
void display( ) ;
inl count( ) ;
-Iinklisl( ) ;
} ;
cout temp ->data ' . ;
temp =temp ->link ;
/I concatenate the second list after the first
temp -> link = I.p ;
II traverse the entire first linked list
while( temp ->link 1= NULL)
temp =temp ->link;
node "temp;
II points tothe starting of the first list
temp =p;
/I if the first linked list is empty
if ( P==NULL)
P=I.p ;
II if both linked lists are non-empty
if ( I.p !=NULL)
{
/I traverse the entire linked list
while ( temp !=NULL)
{
cout endl ;
node "temp =p ;
}
I.p= NULL ;
else
{
/I displays the contents of the linked list
void Iinklist :: display( )
{
Data Structures Through C++
p=NULL ;
/I assign data tothe last node
temp -> data = num ;
temp ->link =NULL ;
/Iadd node at the end
temp ->link = new node ;
temp =temp ->link;
temp =new node :
p=temp ;
/I gotolast node
while ( temp ->link !=NULL)
temp =temp ->link;
}
else
{
/I if the list isempty, create first node
if ( temp == NULL)
{
node -temp ;
temp =p;
192 11'-- ---::::..-.-_
II adds a node at the end of alinked list
void linklist :: append ( int num )
{
/Iinitializes data members
linklist :: linklist( )
{
}
/I concatenates two linked lists
void Iinklist :: concat ( linklist &1 )
{
1/ counts the number of nodes present inthe linkedlist
int Iinklist :: count( )
{
linklist 12 ;
12.append ( 5) ;
12.append ( 6) :
12.append ( 7) ;
12.append ( 8) ;
cout "\nEl ements infirst linked list: ;
11 .display( ) ;
cout "\nNo. ofelements infirst linkedlist: " 11.count( ) ;
cout "\n\nElements insecond linked list:" ;
12.display( ) ;
cout "\nNo. of elements insecond linked list: 12.count( ) ;
II the result obtained after concatenation isinthe first list
11 .concat ( 12 ) ;
cout "\n\nElementsinfirst linkedlist after concatenation: ;
11 .display( ) ;
Chapter 4: Linked Lists
Elements infirst linked list after concatenation:
1 234 5 678
Output:
Elements infirst linked list:
1 234
No. of elements infirst linked list =4
Ele-nents insecond linked list:
567 8
No. of elements insecond linked list =4
- - - - - - - - - - - - I ~ Data Structures Through C++
return c :
node tq:
\vhile( p,= NULL)
{
1/ traverse the entire linked list
while (temp ,= NULL )
{
q=p.> link :
delete p;
p=q ;
intc =0 ;
node -temp=p;
linklist 11 ;
temp=temp -> link ;
c++ :
11 .append ( 1) :
11 .append( 2) ;
11.append ( 3) ;
11 .append ( 4) ;
~ I
-----------------=--
II deallocates memory
Iinkfist :: -Iinkl ist( )
{
voidmain()
{
}
else
{
linktist( ) ;
void append ( int num ) ;
intlength( ) ; .
static intgetlength( node "ptr ) :
-linklist( ) ;
/I add node atthe end
temp -> link =new node ;
temp =temp -> link;
/I gotolast node
while ( temp .>link !=NULL)
temp =temp -> link ;
temp =new node ;
p=temp ;
node "temp =p;
II if the listisempty, create first node
if ( temp == NULL)
{
p=NULL ;
public :
/I adds anode atthe end of alinked list
void Iinklist :: append ( intnum )
{
} ;
II initializes data memebr
linklist :: linklist( )
{
}
Chapter 4: Linked Lists
- - - : . . . . . . - - - - - - - - - - I ~
Data Structures Through C ~ +
Some of the operations that are carried out on linked lists can be
easily implemented using recursion. For example, finding out the
number of nodes present in a linked list, comparing two linked
lists, copying one linked list into another, adding a new node at the
end of the linked list, etc. Given below are the programs for
carrying out each 0 f these operations.
Note that in each of the program given below, we have defined a
static member funct ion to carry out the desired operation using
recursion. We have called this function through another non-static
function , which in tum is called through an object of the class. The
programs have been suitably commented. Hence, we would omit
the discussion about working of each of these programs.
int data ;
node "link;
} 'p ;
In C++, it is possible for the functions to call thems elves. A
function is called 'recursive' if a statement within the body of u
function caJls the same function. Somet imes called 'circular
definition', recursion is thus the process of defining something ill
terms of itself.
(a) Program to find the number of nodes in the linked list using
recursion
/I structure containing adata part and link part
struct node
{
private :
#include <iostream.h>
class Iinklist
{
~ I ~ --------=---=
Recursive Operations On Linked List
II counts the number of nodes inalinked list
intlinklist :: getlength ( node 'ptr )
{
private :
/I structure contai ning data part and link part
struct node
{
#i nclude<iostrearn.h>
public:
linklist{ ) ;
void append ( int num ) ;
linklist I;
I.append ( 1) ;
I.append ( 2) ;
I.append ( 3) ;
I.append ( 4) :
I.append ( 5) ;
cout '\nLength of linked list: l.Iength( ) ;
int data ;
node 'link:
} 'p ;
(b) Programto compare two linked lists using recursion
class linklist
{
Output:
Lengthoflinked list: 5
voidmain{)
(
( 'hapter 4: Linked Lists
- - - - - - - - - - - I ~
~ - - - - - - - - - - - - - - -
Data Structures Through CH
return getlength( p) ;
/I go tonext node
I = 1+getlength ( ptr->link );
return ( I) ;
staticint I;
node 'q ;
II if list isempty or if NULLis encountered
if( ptr== NULL)
return ( 0) ;
else
{
q=p.> link;
delete p;
p=q ;
/I assign data to the last node
temp ->data =num ;
temp -> link =NULL;
/I calls gellength
int linklist :: length( )
{
}
}
while ( p !=NULL)
{
~ I
'----------------....::....._::....:..2....:.....:.._
}
/I deallocates memory
linklist :: -linklist( )
{
intoperator == (linklist &1 ) ;
static int compare ( node "plr1 , node ptr2 ) ;
-linklist() ;
q=P->link;
delete p ;
p=q;
if ( q== NULL II r == NULL)
flag:: a ;
if ( q-> data != r .> data)
flag =a;
else
compare ( q->link, r ->link) ;
}
return ( flag) ;
stalic intflag ;
node tq ;
return compare ( p, I.p ) :
jf ( q::= NULL && r:::: NULL )
flag =1 ;
else
{
while ( p!=NULL)
{
II deallocates memory
linklist :: -linklist( )
{
II calls compare
int Iinklist :: operator == ( linklist &1 )
{
/I compares 2linked lists and returns 1if
II linked lists are equal and 0if unequal
intlinklist .: compare ( node "q. node "r )
{
Data Structures Through C++
p=NULL ;
/I add node at the end
temp ->link =new node;
temp> temp ->link;
temp =new node;
p= temp;
II go tolast node
while ( temp .> link !=NULL)
temp =temp ->link :
node "temp:: p;
II if the list isempty, create first node
jf ( temp == NULL)
{
}
else
{
II assign data tothe last node
temp ->data =num ;
temp ->link =NULL ;
200 I I L . - ~ ~ ~ __~ _ ~ - = - _
} ;
/I initializes data member
linklist :: linklist( )
{
}
/I adds anode atthe end of alinked list
void linklisl .: append ( intnum)
{
temp =new node ;
p =temp ;
1/ add node at the end
temp ->link =new node;
}.p ;
II gotolast node
while ( temp ->link !=NULL)
temp =temp ->link ;
Iinklist( ) ;
void append ( int num ) ;
void fun ( Iinklist &1 ) ;
static void copy ( node ptr1 , node ""ptr2 ) ;
void display( ) :
-Iinklist( ) ;
node "temp ;
temp =p ;
public :
p =NULL ;
II if the list isempty, create first node
if (temp == NULL)
{
}
else
{
/Iinitializes data member
linklist :: linklist( )
{
}
};
II adds anode at the end of the linked list
void linklist :: append ( int num )
{
Data Structures Through C++
11 .append ( 1) ;
11.append ( 2) ;
11 .append ( 3 ) ;
linklist 11 ;
int data ;
node "link;
II structure containing adata part and link part f
struct node
{
Iinklistl2 ;
12.append ( 1) ;
12.append ( 2) ;
12.append ( 3) ;
if ( 11 == 12 )
cout "\nBoth linked lists are equal" ;
else
cout "\nBoth linked lists are different ;
private :
202 111...- -..:::.-__
void main()
{
(c) Program to copy one linked list into another using recursion.
#include <iostream.h>
class Iinklist
{
Output:
Both linked lists are equal
/Icopies alinked list into another
void Iinklist :: copy ( node "ptr1, node "ptr2 )
{
.
II I i
temp =temp ->link ;
q=P-> link;
delete p;
p= q;
cout "\nElements insecond linked list: ;
12.display( ) ;
linklist 12;
12.fun ( 11 ) ;
linklist 11 ;
cout "\nElements infirsllinked list: ;
11 .display( ) ;
11.append ( 1) ;
11.append ( 2) ;
11.append ( 3) ;
11 .append ( 4) :
11 .append ( 5) :
11 .append ( 6) ;
11 .append ( 7) ;
node *q ;
while ( p! ~ NULL)
{
void main()
{
II deallocates memory
Iinklist :: -Iinklist{ )
{
Data Structures Through C+ ,
copy ( l.p, &p ) ;
ptr2 =new node ;
/Itraverse the entire linked list
while ( temp !=NULL)
{
cout endl ;
node "temp =p:
cout temp ->data " " ;
(*ptr2) -> data =ptr1 -> data ;
(*ptr2) ->link =NULL;
copy ( ptr1 ->link, &( ( *ptr2 ) ->link) ) ;
II assign data tothe last node
temp ->data =num :
temp -> link =NULL ;
if ( ptr1 !=NULL)
{
temp =temp -> link:
204 111...- --=-_ _
/I calls copy tocopy alinked list into another
void Iinklist :: fun ( Iinklist &1 )
{
}
If displays the contents ofthe linked list
voidlinklist :: display( )
{
};
private ;
addatend ( &p, num ) ;
node'q ;
}
else
addatend ( &(( 'ptr ) ->link ), num ) ;
('ptr) =new node ;
('ptr) -> data =num ;
("ptr) ->link =NULL;
if ( 'ptr == NULL)
{
cout temp ->data ' " :
temp =temp ->link ;
II traverse the entire linked list
while( temp !=NULL)
{
/I callsaddatend
void linklist :: add ( int num )
{
}
II displays the contents of the linked list
voidIinklist :: display( )
{
cout endl ;
node "temp =p ;
II adds a new node at the end of the linked list
void linklisl :: addalend ( node "ptr, inl num )
{
/1 deallocales memory
linklist :: -linklisl( )
{
Data Structures Through C+ I
p=NULL ;
206 II

linklist( ) ;
void add ( int num ) ;
static void addatend ( node "'ptr, int num) ;
void display( ) ; .
-linklist( ) ;
II structure containing data part and link part
struct node
{
public :
intdata;
node 'Iink;
} 'p ;
Output:
Elements infirst linked list:
1 234 5 5 7
Elements insecond linked list:
1 234 567
(d) to add a new node at the end of linked list using
recursion,
#include <iostream.h>
class linklist
{
II initializes data member
!inklist :: linklist( )
{
}
cout "\nElements inthe linked list: " ;
I.display( ) :
11209
Chapter 4: Linked Lists
dnode 'prev ;
in!data;
dnode next ;
l 'p:
public :
private:
II structure representing a node of the doubly linked list
struct dnode
{
have to traverse the list right from the first node. To avoid this we
can store in each node not only the address of next node but also
the address of the previous node in the linked list. This
arrangement is often known as a 'Doubly Linked List' and is
shown in Figure 4-24.
Figure 4-24. Doubly linked list .
#include <iostream.h>
The following program implements the Doubly Linked List
(DLL).
class linklist
{
Node
I prey Idata Inext I
I N 1 11 1100 200 I 2 1400 100 I 14 I 500 I
200 100 400
Data Structures Through C++
linklist I;
q=P-> link;
delete c:
p = q ;
while ( p!=NULL)
{
208 IIL- --:::....__
I.add ( 1) ;
I.add ( 2) ;
I.add ( 3) ;
I.add (4);
I.add ( 5) :
I.add (6) ;
I.add ( 10) ;
void main()
{
In the linked lists that we have used so far each node provides
information about where is the next node in the list. It .has no
knowledge about where the previous node lies in memory. If we
are at say the 15
th
node in the list, then to reach the 14
th
node we
Output:
Elements inthe linked list:
1 2 3 4 5 6 10
Doubly Linked Lists
q ::: q.> next ;
/I add a new node at the end
r::: new dnode ;
r-> data::: num ;
r ->next ::: NULL;
r ->prev =q ;
q->next ::: r ;
/I skip todesired portion
for ( int i ::: 0 ; i <loe ; itt )
{
dnode "q;
q=p;
II create a new node
q::: new dnode ;
/I assign data and pointer tothe new node
q->prev =NULL;
q->data>num ;
q.> next- p ;
/I make newnode the head node
p->prev =q;
p=q ;
dnode'q;
II adds anew node after the specified number of nodes
void linklist :: d_addafter ( int toe, int num )
{
II adds a new node at the begining of the linked list
void linklist :: d_addatbeg ( int num )
{
Data Structures Through C++
II traverse the linked list till the last node isreached
Ilcreate anew node
q ::: new dnode ;
q->prev ::: NULL ;
q->data s num ;
q->next ::: NULL;
p:: q;
while ( q->next f:: NULL)
q::: q->next;
p::: NULL ;
linklist() ;
voidd_append ( int num ) ;
void d_addatbeg ( int num ) ;
void d_addafter ( int loc, intnum ) ;
void d_display( ) ;
int d_count( ) ;
void d_delete( int i ) ;
-linklist() :
}
else
{
dnooe "r, -q :
q > p:
II if the linked list isempty
if ( q:::::: NULL)
{
210 11'---- ----"-_ _
/I initializes data member
linklist :: linklist( )
{
II adds anew node at the end of thedoubly linked list
void linklist :: d_append ( intnum )
{
q-> prey -> next :: q-> next ;
q->next -> prey :: q-> prey ;
/Iif node tobe deleted is found
if ( q-> data == num )
{
/I if nodetobedeleted is the first node
if( q ::= p)
{
II if node tobe deleted isthe last node
if ( q-> next == NULL)
q-> prey-> next > NULL ;
else
/I if node tobedeleted is any intermediate node
{
ternp > temp -> next ;
c++ ;
p:: p->next ;
p->prey :: NULL :
}
else
{
return c :
dnoce tq> p:
II traverse theentirelinked list
while ( temp !=NULL)
{
1/ traverse theentirelinked list
while( q !=NULL)
{
1/ deletes the specified node fromthe doubly linkedlist
void linklist :: d_delete ( inl num )
{
Data Structures Through C++
II insert new node
q=q->prev :
dnode "temp =new dnode ;
temp -> data =num ;
temp ->prey :: q ;
temp .> next =q->next ;
temp -> next -> prey =temp ;
q-> next :: temp ;
II if end of linked list isencountered
if ( q == NULL)
{
./
cout "\nThere areless than" loc elements" :
return ;
dnode 'temp>p:
cout temp -> data' ":
temp> temp ->next ;
cout endl ;
1/ traverse the entirelinked list
while ( temp 1= NULL )
{
212 II'-- - - - - . . . . . . : : ~ _
1/ displays the contents of thelinked list
void Iinklist :: d_display( )
{
II counts thenumber of nodes present inthe linked list
int linklist :: d_count( )
{
int c > 0;
dnode 'temp> p ;
cout "InElements indoubly linked list: " ;
I.d_display( ) ;
coot "'nlnElements inthedoubly linked listafter deletion: :
I.d_display( ) ;
cout "InNo. of elements inthe doubly linked list: " I.d_count( ) ;
I.d_delete ( 55) ;
I.d_delete ( 2) ;
I.d_delete ( 99 ) ;
cout ; "InNo. of elements inthe doubly linked list: " I.d_count( ) ;
cout "\nlnElements inthe doubly linked listafter addition
at the given position: ;
I.d_display( ) ;
ccot "InNo. of elements inthe doubly linked list: " I.d_count( ) ;
I.d_addafter ( 4, 66) ;
I.d_addafter ( 2, 96) ;
cout inlnElements inthe doubly linked listafter addition
at the beginning: ;
I.d_display( ) ;
cout "InNo. of elements inthe doubly linked list: " I.d_count( ) ;
I.d_addatbeg ( 33 ) ;
I.d_addatbeg ( 55 ) ;
Elements inthe doubly linked listafter addition at the beginning:
55 33 11 2 14 17 99
No. of elements inthe doubly linked list: 7
Elements inthe doubly linked listafter addition at the given position:
Output:
Elements inthe doubly linked list:
11 2 14 17 99
No. of elements inthe doubly linked list: 5
Data Structures Through C++
q =P->next ;
delete p;
p=q ;
while ( q ->next !=NULL)
{
II gotonext node
q =q->next ;
}
cout "\n" num " not found." ;
delete q ;
II retum back after deletion
return :
linklist I ;
I.d_append ( 11 ) ;
I.d_append ( 2) ;
I.d_append ( 11 ) ;
I.d_append ( 17) ;
I.d_append ( 99 ) ;
214 II
' - - - - - - - - - - - - _ - - - . : . . . . . ~ : . : . : . . : ! . . : . . : . . . . . = . -
II deallocates memory
linklist :: -Iinklist( )
{ .
dnode tq :
void main()
{
The statement r -> prev -- q makes the prev part cof the new node
r to point to the previous node q. The statement q -> next = r
makes the next part of q to point to the last node ~ . This is shown
in Figure 4-25.
r-> prey =q;
q->next =r;
q is made to point to the last node of the list. lThen memory is
allocated for the node whose address is stored in r. A NULL value
is stored in the next part of this node, because thi..s is going to be
last node. Now what remains to be done is to l i ~ this node with
rest of the list. This is done through the statements
Data Structures Through C++ 216 11 ----=:::...__
The d_append( ) function adds a node at the end of the existing
list. It also checks the special case of adding the first node if the
list is empty. This function accepts a parameter nurn, which holds
an integer to be added to the list.
If the list is non-empty then through the statements
Let us now understand the different functions that we have defined
in the program. Let us begin with the one that appends a new node
at the end of a double linked list.
Elements inthe doubly linked list after deletion:
33 96 11 66 14 17
No. of elements inthe doubly linked list: 6
55 33 96 11 2 66 14 17 99
No. of elements inthe doubly linked list: 9
Function d_append()
while ( q.> next !=NULL)
q =q.> next ;
To begin with we initialize q which is of the type struct dnode *
with the value stored at p. This is done because using q the entire
list is traversed if it is non-empty.
If the list is empty then the condition
if ( q== NULL)
gets satisfied. Now memory is allocated for the new node whose
address is stored in q (i.e. p). Using q a NULL value is stored in
its prcv and next links and the value of nurn is assigned to its
data part.
Figure 4-25. Doubly linked list addffion of a node.
, :
The d_addatbeg( ) function adds a node at the beginning of the
existing list. This function too accepts parameter num, which
holds an integer to be added to the list.
Function d addatbeg()
Memory is allocated for the new node whose address is stored in
q. Then num is stored in the data part of the new node. A NULL
value is stored in prev part of the new node as this is going to be
[he first node of the list. The next part of this new node should
contain the address of the first node of the list. This is done
through the statement
q-> next =p;
Now what remains to be done is to store the address of this new
node into the prev part of the first node and make this new node
the first node in the list. This is done through the statements
P->prey =q;
p=c:
These operations are shown in Figure 4-26.
New node
r
r
q
q
Before Addition
After Addition
p
~
New node
Data Structures Through (' f ..
Before Appending
After Appending
Addition of new node at the end
p
p
Case I: Addition to an empty linked list
Related Function: d_append( )
p =s =NULL
Case /I: Addition to an existing linked list
Related Function: d_append( )
I I
I'
"
I ; ,
i '
.,
. i
q=q-:> prev ;
makes q to point to the node after which the new node should be
added. Then memory is allocated for the new node and its address
is stored in temp. The value of num is stored in the data part of
the new node.
A loop is executed to reach the position where the node is to be
added. This loop also checks whether the position loc that we have
mentioned, really occurs in the list or not. When the loop ends, we
reach the loe position where the node is to be inserted. By this time
q is pointing to the node before which the new node is to be added.
The statement
The d_addafter( ) function adds a node at the specified position of
an existing list. This operation of adding a new node in between
two existing nodes can be better understood with the help of
Figure 4-26. This function accepts two parameters. The first
parameter loc specifies the node number after which the new node
must be inserted. The second parameter num is an integer, which
is to be added to the list.
Function d_addafter()
The prev part of the new node should point to q. This is done
through the statement
temp -:> prev =q;
The next part of the new node should point to the node whose
address is stored in the next part of node pointed to by q. This is
achieved through the statement
temp -:>next =q-:> next ;
Now what remains to be done is to make prev part of the next
node (node pointed by q -> next) to point to the new node. This is
done through the statement
Data Structures Through C++
New node
After .Insertion
Before Insertion
q temp
Addition of new node at the beginning
Related Function: d_addatbeg()
p
Before Addition
p
temp
~
After Addition
Insertion of new node after a specified node
Related Function: d_addafter()
pq
q
~
New node
pq
220 IIL =____
Figure 4-26. Working of d_addatbeg( } and d_addatbeg( }
functions.
previous node and the address of the previous node is stored in the
prey part of the next node. This is done through the statements
Finally the memory occupied by the node being deleted is released
by calling the delete operator. Figure 4-27 shows the working of
the d_delete( ) function.
q-> prey ->next =q-> next ;
q-> next ->prey =q-> prey ;
Data Structures Through C++ 222 11 ......:::...-__
The function d_delete( ) deletes a node from the list if the data
part of that node matches num. This function receives the number
that is to be deleted from the list.
If the node to be deleted happens to be any intermediate node, then
the address of the next node is stored in the next part of the "
Function d_delete()
We run a loop to traverse the list. Inside the loop the data part of
each node is compared with the Dum value. If the num value
matches the data part in the node then we need to check the
position of the node to be deleted.
temp ->next -> prey =temp ";
At the end, we change the next part of the q to make it point to the
new node, and this is done through the statement
q->next =temp ;
if ( q.> next == NULL)
q->prsv-> next =NULL;
If it happens to be the first node, then the first node is made to
point to the next part of the first node. This is done through the
statement
p=P->next;
Then, a value NULL is stored in prey part of the second node,
since it is now going to become the first node. This is done
through the statement
p->prey =NULL ;
If the node to be deleted happens to be the last node, then a value
NULL is stored in the next part of the second last node. This is
done through the statements
1/ initializes data member
};
If structure containing data part and link part
struct polynode
{
private:
float coetf ;
int exp;
polynode link:
}.p ;
poly() ;
void poly_append ( fioat c, inte) ;
void display_poly( ) ;
void poly_add( poly &11, poly &12 ) ;
-poly() ;
class poly
{
#include <iostream.h>
public :
Polynomials like 5x
4
+ 2x
3
+ 7x
2
+ l Ox - 8 can be maintained U5ing
a linked list. To achieve this each node should consist ofthree
elements, namely coefficient, exponent and a link to the next term.
While maintaining the polynomial it is asswned that the exponent
of each successive term is less than.that of the previous term. Once
we build a linked list to represent a polynomial we can use such
lists to perform common polynomial operations like addition and
multiplication. The program that can perform these openlUO
ns
is
given below.
Linked Lists And Polynomials
Data Structures Through C++
Node to be deleted 14
pq
Node to be deleted 33
Before Deletion
p
Before Deletion
After Deletion
Deletion of node
Case I: DeletloD of first node
Related Function: d_delete( )
pq
After Deletion
Case II: Deletion of last node
Related FunctIon: d_delete()
224 II
- - - - - _ - - = - . : : : . : . . : . . . : : . : . : . . . . : . : = . : . . . . : : . . . . : . : : : . : . . . : : : : ~ : . . . : . . . : . -
Figure 4-27. Worl<ing of d_de/ete() function
I '
if ( f !=0 )
{
II display sign of aterm
if ( temp ->coeff > 0)
cout- ' +. ;
else
cout ;
}
if ( temp ->exp !=0)
cout temp ->coeff x" temp .> exp ;
else
cout temp ->coeff ;
temp =ternp-> link;
f = 1 ;
polynode "z;
/I if roth linked lists are empty
if ( l1.p == NULL && 12.p == NULL)
return ;
II traverse till one of the listends
polynode "temp1. "lemp2 ;
temp1 =l1.p ;
temp2 =12.p;
while( temp1 !=NULL && temp2 !=NULL)
{
cout endI ;
II traverse till the end of the linked list
while ( temp !=NULL)
{
/I adds two polynomials
void poly :: poly-add ( poly &11, poly &12 )
{
Data Structures Through C++ =
p =NULL;
/I traverse the entire linked list
while ( temp ->link !=NULL)
temp =temp ->link;
/I assign coefficient and exponent
temp ->coeff =c ;
temp ->exp =e ;
temp ->link =NULL ;
temp =new polynode ;
p=temp;
}
else
{
II create new nodes at intermediate stages
temp ->link =new polynode ;
temp =temp -> link ;
/I creates anew node if the listisempty
if ( temp == NULL)
{
polynode "temp =p ;
intf == 0 ;
polynode "temp =p ;
poly :: poly( )
{
}
II adds aterm toapolynomial
void poly :: poly-append (floatC,inte)
{
II displays the contents of linked list representing apolynomial
void poly :: display-po1y() -,
{
, I
: I I
p=new polynode ;
z=p;
if ( p== NULL)
{
/I gotothe next node
lemp1 =temp1 ->link ;
II assigning the added coefficient
z->coeff =temp1 ->coeff +temp2 ->coeff;
z->exp =temp1 ->exp :
/I assign coefficient and exponent
z->coeff =temp1->coeff ;
z->exp =temp1 ->exp ;
/I go to the next node
temp1 =temp1 ->link;
temp2 =temp2 ->link;
Z->link =new polynode :
z=z-> link ;
}
else
{
II assign remaining terms of the
/I first polynomial tothe result
while (temp1 !=NULL)
{
1/ assign remaining terms of
1/ second polynomial to the result
while ( temp2 !=NULL)
Data Structures Through C++
}
else
{
Z ->link =new polynode ;
z=Z ->link;
if (temp1 .> exp >temp2 ->exp)
{
z->coeff =temp1->coeff ;
z->exp =temp1 -> exp ;
/I go tothe next node
temp2 =temp2 ->link;
/I goto the next node
temp1 =temp1 ->link;
/I create anew node if the list isempty
if ( P== NULL)
{
p=new polynode ;
z=p;
II add the coefficients, when exponents are equal
if (temp1 ->exp == temp2 ->exp )
{
/I create new nodes at intermediate stages
else
{
/I store aterm of the larger degree polynomial
if ( temp1 ->exp <temp2 ->exp }
{
z->coeff =temp2 ->coeff ;
z->exp =temp2 ->exp ;
}
else
{
228 11 -=..._ _
II assign NULL at end of resulting linked list
z->link =NULL ;
poly p1 ;
p1.poly-append ( 1.4, S) ;
p1 .poly_append ( 1.S, 4) ;
p1 .poly-append (1.7,2) ;
p1 .poly_append ( 1.8, 1) ;
p1.poly_append ( 1.9.0) ;
cout "InFirst polynomial:" ;
p1.display_poly( ) ;
poly p2 ;
p2.poly_append ( 1.S, 6) ;
p2.poly-append ( 2.S, S) ;
p2.poly_append ( -3.S, 4 ) ;
p2.poly_append ( 4.S, 3) ;
p2.poly_append ( 6.S, 1) ;
cout '\nSecond polynomial:" ;
p2.display-poly( ) ;
poly p3;
p3.poly-add ( p1 , p2) ;
cout inResullant polynomial : " ;
p3.display-poly( ) ;
Output:
First polynomial :
1.4x"S +1.Sx"4 +1.7x"2 +1.8x"1 +1.9
Second polynomial:
1.Sx"6 +2.Sx"S -3.Sx"4 +4.Sx"3 + 6.Sx"1
Resultant polynomial :
1.Sx"6 +3.9x"S -2x"4 +4.Sx"3 + 1.7x"2 + 8.3x"1 + 1.9
Data Structures Through C++
II assign coefficient and exponent
z->coeff =temp2 ->coeff ;
z->exp =temp2 ->exp ;
II goto the next node
temp2 =temp2 -> link;
p=new polynode ;
z=p :
}
else
{
jf ( p== NULL)
{
Z->link =new polynode ;
z =Z-> link ;
q=P-> link;
delete p;
p=q;
polynode 'q ;
while ( p!=NULL)
{
230 I I I - - - - - ~ - - = - - - - - -
II deallocates memory
poly :: -poly( )
{
void main()
p=NULL;
II traverse the entire linked list
while ( temp ->link != NULL)
temp =temp ->link;
float coeff ;
intexp ;
polynode "link ;
}.p;
public:
poly() ;
void poly_append (floatc. inte) ;
void display-POly( ) ;
void poly-multiply ( poly &p1, poly &p2 ) ;
void padd ( float c, int e) ;
-poly() ;
temp =new polynode ;
p=temp;
polynode "temp ;
temp =p:
II create anew node if the list isempty
if ( temp =NULL)
{
}
else
{
_ .. _ - - - - - - - - - - - - - - - - - - - - - - - - - _ . ~ -
};
/Iinitializes data member
poly :: poly( }
{
}
/I adds aterm toapolynomial
void poly :: poly_append (float c, inte)
{
Dara Structures Through C++
232 11'--- --=-__
private :
Here the class poly contains a structure polynode to represent each
tenn in the polynomial. The structure contains the coefficient and
exponent value of a term and a pointer to the next node. Let us
now see the working of poly_append( ) and ploy_add( )
functions.
/I structure containing data part and link part
struct polynode
{
In this program the poly_appeod( ) function is called several
times to build the two polynomials contained in pl and p2. Next
the function poly_add( ) is called to carry out the addition of two
polynomials. In this function the linked lists representing the two
polynomials are traversed till the end of one of them is reached.
While doing this traversal the polynomials are compared on term-
by-term basis. If the exponents of the two terms being compared
are equal then their coefficients are added and the result is stored
in the third polynomial p3. If the exponents of two tenns are not
equal then the tenn with the bigger exponent is added to the third
polynomial. During the traversal if the end of one of the list is
reached the control breaks out of the while loop. Now the
remaining terms of that polynomial whose end has not been
reached are simply appended to the resulting polynomial. Lastly,
the terms of the resulting polynomials are displayed using the
function display-poly( ).
Let us now see a program to carry out multiplication of the two
polynomials.
#include <iostream.h>
class poly
{
polynode *temp1, -temp2 ;
float coeftt, exp1 ;
/I point tothe starting of first linked list
temp1 =p1.p ;
if ( temp2 =7= NULL)
P=temp1 ;
else /Iif both linked lists exist
{
/I rnultiply each term of the second linked list
1/ with aterm of the first linked list
while ( temp2 != NULL)
{
/I for each term of the first list
while (temp1 !=NULL)
{
coeff1 =temp1 ->coeff temp2 .> coeff ;
exp1 =temp1 ->exp +tempz-> exp ;
temp2 =temoz-> link;
/I add the new tenn tothe resultant polynomial
padd ( coeftt , exp1 ) ;
/Ipoint tothe starting of second linked list
temp2 =p2.p ;
if (temp1 == NULL && temp2 == NULL)
return ;
/Iif one of the listisempty
if (temp1 == NULL)
P=p2.p;
else
{
Chapter 4: Linked Lists
/I multiplies the two polynomials
void poly :: poly-multiply ( poly &p1. poly &p2 )
{
Data Structures Through C++
/I display sign ofatenn
if ( temp ->coeff > 0)
cout' +';
else
cout" ;
}
if ( temp ->exp != 0)
cout temp ->coeff ' x ~ ' temp ->exp ;
else
cout temp ->coeff ;
temp =temp -> link;
f =1;
if ( f != 0)
{
/I traverse till the end of the linked list
while (temp != NULL)
{
1/ create new nodes atintennediate stages
temp .> link =new polynode ;
temp =temp .> link ;
1/ assign coefficient and exponent
temp ->coeff =c ;
temp ->exp =e;
temp ->link =NULL;
1/ displays the contents of linked listrepresenting apolynomial
void poly :: dlsplaYJlOly()
{
polynode -temp =p;
intf =0 ;
234 IIL..- ---'='---
1/ reposition the pointer tothe starting of
1/ the second linked list
temp2 =p2.p ;
r :: newpolynode ;
r ->coeff =c;
r ->exp =e;
r ->link =NULL;
temp->link= r;
retum;
1/ gotonext node
temp =temp ->link;
if ( temp .> exp >c&& ( temp -> link -> exp c CII
ternp-> link == NULL) )
if ( temp ->exp == e)
{
temp .>coeff += c ;
retum:
II traverse the entire linked list to
II search the position toinsert anew node
while ( temp != NULL)
{
r> link:: NULL;
temp -> link =r ;
polynode -q ;
while ( p!= NULL)
{
II deallocates memeory
poly :: -poly( )
{
Data Structures Through C++
polynode -r, -temp:
temp =p;
r .>link =NULL;
p:: r:
}
else
r =new polynode ;
r ->,coeff =c ;
r ->exp =e;
if (p == NULL)
{
II gotothe next node
temp1 =temp1 .>link;
}
else
{
r -> link:: temp;
p=r;
II if list isempty orif the node istobe
II inserted before the first node
if (temp == NULL II C>temp ->exp )
{
236 IIL..-- ~ __
/I adds aterm tothe polynomial in
/I the descending order of the exponent
void poly :: padd ( float c, inte)
{
I
, I
Function poly_multiply()
Resultant polynomial:
3x"11 +8x"10 +13x"9+ 7x"8 +2x"7 +3x"6
This function receives two parameters, each a reference to the
object of poly class. Two variables coeffI, expl are supposed to
hold the value of coefficient and exponent of the current resultant
node. The pointers templ and temp2 point to the first node of the
linked list contained in pI and p2 respectively.
In this program once again the poly_append( ) function is called
to build the two polynomials. Followed by this, the
polYJllultiply( ) function is called to carry out the multiplication
of the two polynomials contained in pI and p2. In this function if
it is found that both the linked lists (representing the two
polynomials being multiplied) are non-empty then the control goes
in a pair of wbile loops. Here each term of the second polynomial
is multiplied with every term of the first polynomial. As this
proceeds and a new term is built, the function padd( ) is called to
add this term to the resulting polynomial. In padd( ) each term of
the existing resulting polynomial is scanned to find whether there
exists a term in this polynomial whose exponent is same as that of
the term to be added. If it .is so, then the corresponding coefficient
of the existing polynomial is updated, otherwise the new term is
simply appended to the end of the existing polynomial. Yet again
the resulting polynomial is displayed using the function
display....poly( ). The functions poly_multlply( ) and padd( ) are
explained as follows:
A condition is checked whether both the lists are empty or not. If
both the lists are found to be empty then the control returns back.
If the condition to check if both the lists are non-empty evaluates
to true, then a condition is checked whether either of the two lists
is empty or not. If one of the two lists is found to be empty then
the pointer of the resultant list p is made to point to another list.
Data Structures Through C++
cout "\nResullant polynomial: " endI ;
p3.displaY-POly() ;
ccut <.<. "\nSecond polynomial: endl ;
p2.display_poly() ;
poly p3;
p3.poly_multiply ( p1, p2) ;
cout "\nFirst polynomial: " endl ;
p1.display_poly() ;
poly p2;
p2.poly_append ( 1, 6) ;
p2.poly-append ( 2, 5) ;
p2.poly_append ( 3, 4) ;
q =p.> link;
delete p;
p=q;
poly p1 ;
p1.poly_append (3,5);
p1 .poly-append ( 2, 4) ;
p1 .poly_append ( 1, 2) ;
Output:
First polynomial:
3x"5 +2x"4 +1x"2
Second polynomial:
1x"6 +2x"5 +3x"4
}
void main()
{
}
238 11e-..----------=----
, I
I
, I
I
(
.:
"
I
I'
I
,\
'.
f
, I
The process of searching the proper position to insert a node is
exactly same as explained in the the linked
list in ascending order, the only difference IS t1\at there the list was
maintained in ascending order and here i"t 'is maintained in
descending order.
simply the coefficient parts are added. If it -does not exist then
memory is allocated and a new node is inserted...
Exercise
IA] State whether the following statements are True or False:
(a) Linked list is used to store similar data.
(b) All nodes in the linked list must always in non-contiguous
memory locations.
(c) It is necessary that the link part of the last node in a linked list
must contain NULL.
(d) In a singly linked list, if we losing the location of the first
node is as good as having lost the entire lil)ked list.
(e) Doubly linked list facilitates movement from one node to
another in either direction.
(f) A doubly linked list will occupy less as compared to a
corresponding singly linked list.
(g) If we were to traverse from first node to last node it would be
faster to do so if the linked list is linked instead. of
doubly linked.
(h) In a structure used to represent the node Ofa doubly linked list '
it is necessary that the structure elemellts are in the order
backward link, data, forward link.
(i) If a pointer p were pointing to one of th\: nodes in a circular
linked list, then moving the pointer to the next node would
cause a memory leak.
Data Structures Through C++
To begin with we initialize a structure pointer temp with a value p,
where p is pointer to the first node of the resultant list. Its value
would be NULL when called for the first time.
..
Function padd()
If both the lists exist then a while loop is executed which runs till
the end of the first list (i.e. tempi != NULL). First time through
this loop, each term of second list is multiplied with the first term
of the first list. Then the pointer is again repositioned to the first
term of the second list through the statement temp2 = temp2.p.
The job of adding the resultant node to the resultant list is done
through the function padd( ). This process is continued till we do
not have multiplied each term of the first polynomial with the
second polynomial.
This function adds the node to the resultant list (i.e. p3) in the
descending order of the exponents of the polynomial.
If both the above two conditions are false then the resultant list is
traversed for searching the proper position where the new node is
to be inserted. If the exponent of the same order already exists then
Initially a condition is checked whether the resultant list is empty
or not. If it is so then we need to add the first node. Hence memory
is allocated for the new node and the value of coefficient and
exponent is assigned to the coefficient and exponent part of the
new node. temp which holds a NULL value to begin with is stored
in the link part of the resultant new node.
When padd( ) is called to add the second node we need to
compare the exponent value of the new node with that of the first
node. If the exponent value of the new node is greater than the
exponent value of the first node in the resultant list, then the new
node is made the first node.
, 240 II
'-------------------=----
J
.
Write a function add( ) to add these polynomials and print the
resulting linked list.
3x
2y
+ 9xy3 + 15 xy + 3
13 x
3
y2+ 7x
2
y + 22 xy + 9y3
Write a function to combine the two lists such that the
resulting list contains nodes in the following elements:
7,6,5,25,3,32,1,11,20,9
You are not allowed to create any additional node while
writing the function .
(g) A linked list contains some positive numbers and some
negative numbers. Using this linked list write a program to
create two more linked lists, one containing all positive
numbers and the other containing all negative numbers.
(h) Create two linked lists to represent the following polynomials:
(0 There are two linked lists A and B containing the following
data :
A:7,5,3,1,20
B: 6, 25, 32, 11,9
Data Structures Through C++ 242 II'--- _=___
Write a program to create:
A linked list C that contains only those elements that are
common in linked list A and B.
- A linked list D that contains all elements of A as well as B
ensuring that there is no repetition of elements.
(d) Assume a singly linked list containing integers. Write a
function move( ) which would move a node forward n
positions in the linked list.
(e) Write in program to maintain a doubly linked circular linked
list.
[BI Answer the Following:
(a) Write a program to list the current directory in alphabetical
order using a linked list.
Hints:
Use standard library functions findfirst( ) and findnext( ) in
Turbo C++ to read the directory entries.
- Define a structure struct node, which contains the
standard structure struct ffblk defined in file "dos.h" as
data part, and add another element next as link to the
next node.
- When all the directory entries are read and stored in the
linked list, sort the linked list and then display the sorted
linked list.
(b) Write a program that reads the name, age and salary of 10
persons and maintains them in a linked list sorted by name.
(c) There are two linked lists A and B containing the following
data:
A: 3, 7,10,15,16,9,22,17,32
B: 16,2,9, 13,37,8,10,1,28
CHAPTER
Data Structures Through C++
298 IIL --=-- --=-__
(i) Store an element when the row number , column number
and the value is provided.
(i) Retrieve an element for given row and column number of
the matrix.
(ii) Add two sparse matrices
(iii) Subtract two sparse matrices
SIX
Stacks
Of Wad Of Notes
B
e it items in a store, books in a library, or notes in a bank, the
moment they become more than handful man starts stacking
them neatly. It was natural, that when man started
programming data, stack was one of the first structures that he
thought of when faced with the problem of maintaining data in an
orderly fashion. There is a small difference however, data in a
stack is consumed in an orderly fashion; same may not be
necessarily true in case of wads of nodes.
299
DataStructures Through C++
I
~ - - - - - - - - - - - - - - = = = - - ~ -
Opc,..tio Dacrlpti n
Push Allows addingan elementat the top of the stack,
Pop Allowsto removean element fromthe top of the
stac:k
top
13
top
7
top
11 11
8 8 8 8
~
-4
..... ..... -4
top NULL
2 2 2 2
D
Figure 6-2. Pictorial representation of stack after deletion of
elements.
On deletion of elements the stack shrinks at the same end, as the
elements at the top get removed. Figure 6-2 shows how the stack
shrinks on deletion of elements.
Table 6-1. Operations performedon stack.
Operations On Stack
A stack is generally implemented with two basic operations-push
and pop. These are listed in Table 6-1.
2
11
top
top
top
Figure 6-1. Pictorial representation of stackafter insertingelements.
The linear data structure such as an array and a linked list allows us
to insert and delete an element at any place in the list, either at the
beginning or at the end or even in the middle. However, sometimes
it is required to permit the addition or deletion of elements only at
one end, that is either at the beginning or at the end. Stack and
Queue are two types of data structures in which the addition or
deletion of an element is done at end, rather than in the middle.
A Stack is a data structure in which addition of new element or
deletion of an existing element always takes place at the same end.
. This end is often known as top of stack. This situation can be
compared to a stack of plates in a cafeteria where every new plate
added to the stack is added at the top. Similarly, every new plate
taken off the stack is also from the top of the stack. The two
changes that can bemade to a stack are given special names. When
an item is added to a stack, the operation is called push, and when
an item is removed from the stack the operation is called pop.
Stack is also called as last-in-first-out (LII:.QLlist. If the elements
are .added continuously to the stac It grows at one end. This is
shown in Figure 6-1.
Data Structures Through C++
I , - - - ---_---=::_-
top =-1 ;
Before making use of stack in a program, it is very important to
decide how to represent a stack. There are several ways of
representing a stack. Let us see how efficient it is to use an array to
represent a stack.
Stack As An Array
Stack contains an ordered collection of elements. An array is used
to store ordered list of elements. Hence, it would be very easy to
manage a stack if we represent it using an array. However, the
problem with an array is that we are required to declare the size of
the array before using it in a program. This means the size of an
array should be fixed. Stack on the other hand does not have any
fixed size. It keeps on changing, as the elements in stack are
popped or pushed.
Though an array and a stack are totally different data structures, an
array can be used to store the elements of a stack. We can declare
the array with a maximum size large enough to manage a stack. As
a result, the stack can grow or shrink within the space reserved for
it. Let us see a program that implements a stack using an array.
#include <iostream.h>
int pop( ) ;
};
II initialises data member
stack:: stack( )
{
}
II adds an element tothe stack
void stack :: push ( int item)
{
if ( top == MAX - 1)
{
cout endl "Stack isfull" ;
return ;
}
top++ ;
arr[top] =item;
II extracts an element from the stack
intstack:: pop( )
{
const int MAX =10;
class stack
{
private:
int arr[MAX] ;
inttop;
if ( top == -1 )
{
cout endl "Stack isempty" ;
return NULL;
}
intdata =arr[top] ;
top-- ;
return data;
public:
void main()
{
stack() ;
void push ( int item) ;
stack. s ;
-
Data Structures Through C++ 304 11 :::......-_
s.push ( 11 ) ;
s.push ( 23 ) ;
s.push ( -8-) ;
s.push ( 16) :
s.push ( 27 ) ;
s.push ( 14 ) ;
s.push ( 20 ) :
s.push ( 39 ) ;
s.push (2):
s.push ( 15) ;
s.push (7);
inti =s.pop( ) ;
cout "\n\nltem popped: i ;
i =s.poP();
cout -vJltem popped: i; .
i =s.pop{);
cout -vJltem popped: i ;
i =s.poP(}:
cout : "\nltem popped: .i ;
i =s.poP(}:
cout : "\nltem popped: cc i ;
}
Output:
Stack isfull
Item popped: 15
Item popped: 2
Item popped: 39
Item popped: 20
Item popped: 14
Here to begin with we have defined a class called stack containing
member functions push( ) and pop( ). These functions respectively
add and delete items from the top of the stack. The actual storage is
done in an array arr. The data member top is an index into this
array. It contains a value where the addition or deletion is going to
take place in the array, and thereby in the stack. To indicate that to
begin with the stack is empty the variable top is set with a value -I.
Every time an clement is added to stack, it is verified whether such
an addition is possible at all. If it is not then the message 'Stack is
full' is reported. Since we have declared the array to hold 10
elements, the stack would be considered full if the value of top
becomes equal to 9.
In main( ) we have called push( ) function to add 11 elements to
the stack. The value of top would become 9 after adding 10
elements. As a result, the 11th element 7 would not get added to
the stack. Lastly, we have removed few elements from the stack by
calling the pop( ) function.
Stack As A Linked List
In the earlier section we had used arrays to store the elements that
get added to the stack. However, when implemented as an array it
suffers from the basic limitation of an array-that its size cannot be
increased or decreased once it is declared. As a result, one ends up
reserving either too much space or too less space for an array and
in tum for a stack. This problem can be overcome if we implement
a stack using a linked list. In case of a linked stack we shall push
and pop nodes from one end of a linked list.
The stack as linked list is represented as a singly connected list.
Each node in the linked list contains the data and a pointer that
gives location of the next node in the list. The node in the list is a
structure as shown below:
struct node
{
11
i
II
, I
Data Structures Through c++
306 IIL.- -.-;=___
<data type> data ;
node "link;
struct node
{
top>NULL;
where <data type> indicates that the data can be of any type like
int , float, cbar etc, and link, is a pointer to the next node in the
list. The pointer to the beginning of the list serves the purpose of
the top of the stack. Figure 6-3 shows the linked list representation
of a stack.
+
top
[j
23
1
NI
Nstands for NULL
1
r
l
-61
I
J
I
r
l
9
I I I
I
I 10 I I 1
intdata;
node "link ;
} "top ;
public :
Slack() ;
void push ( inl item) ;
int pop{) ;
-stack() ;
} ;
1/ initialises data member
stack :: stack( }
{
}
II adds anew node tothe stack as linked list
void stack :: push ( intitem)
{
node "lemp;
lemp =new node;
I
II
Figure 6-3. Representation of stack as a linked lis/.
if ( temp == NULL)
cout endl 'Stack isfull' ;
Let us nowsec a programthat implements stack as a linked list.
#include <iostream.h>
temp .> data =item ;
temp -> link =top;
top =temp;
class stack
(
private :
II structure containing data part and link part
/I pops an element from the stack
inl stack :: pop( )
{
if ( top == NULL)
I
I
I'
coot cc endl 'Slack isemply" ;
return NULL ;
Chapter 6: Stacks = -----11
309
s.push ( 29) ;
s.push ( 31 ) ;
s.push ( 16) ;
int i =s.pop( ) ;
caul cc "\nltem popped: i ;
Data Structures Through C++
node temp;
int item;
{
308 11rr-------.::---=------
temp =top;
item =temp ->data;
lop=lop->link;
delete temp;
return item;
i =s.poP() ;
cout "\nltem popped: i ;
i =s.pop() ;
coutcc "\nltem popped: cc ] ;
}
}
/I deallocates memory
stack :: -stack( )
{
if ( top == NULL)
return :
node 'temp;
while ( top != NULL)
{
temp =top ;
top =top -> link ;
delete temp;
}
void main()
{
Output:
Item popped: 16
Item popped: 31
Item popped: 29
Here too we have d s igned a. class called stack. The data member
top is a pointer to Q c;- structure node. Initially, top is set to NULL
to indicate that the . tack is empty. In every call to the function
push( ) we are crca l lllg a new node dynamically. As long as there
is enough sPjce fOi .Yn-amic memory allocation temp would never
become NULL II' ' -'1o'Wever the value of temp happens to be
NULL, then that WI I d be a Stage where slack would become full.
After, creating a llt node, the data med1ber top should point to
the newly created I ~ 1 T l of the list. Her.c;e we have assigned the
address of this ne ode to top. The stack as a linked list would
grow as shown in ' I -ire 6-4.
stack s;
s.push ( 14) :
s.push ( -3) ;
s.push ( 18) ;
Data Structures Through C++
top
N stands for =NULL
top
~
rffi)
N stands for =NULL
Figure 6-4. Stack as a /inked list after insertion of elements.
Figure 6-5. Stack as a linked list after deletion of elements.

In the pope ) function, first we are checking whether or not a stack


is empty. If the stack is empty then a message 'Stack is empty' gets
displayed. If the stack is not empty then the topmost item gets
removed from the list. The stack after removing three items from
the list would be as shown in Figure 6-5.
Applications Of Stacks
The place where stacks are frequently used is in evaluation of
arithmetic expression. An arithmetic expression consists of
operands and operators. The operands can be .n u m e ~ i c values . or
numeric variables. The operators used in an arithmetic expression
represent the operations like addition, subtraction, multiplication,
division and exponentiation.
When higher level programming languages came into existence
one of the major hurdles faced by the computer scientists was to
generate machine language instructions that would properly
evaluate any arithmetic expression. To convert a complex
assignment statement such as:
X=A/B +C*D-F*G/Q
Data Structures Through C++
1J1'-
into a correct instruction sequence was a formidable task. That it is
no longer considered so formidable is attribute to the elegant and
simple solutions that the computer scientists came out with. As of
today, this conversion is considered to be one of the major aspects
of compiler writing.
To fix the order of evaluation of an expression each language
assigns to each operator a Even after assigning priorities
how can a compiler accept an expression and produce correct
code?
A polish mathematician Jan Lukasiewicz suggested a notation
called Polish notation, which gives two alternatives to represent an
arithmetic expression. Tlle notat!9.ns are prefix and postfix
JJ91a.tions. The fundamental property of Polish notation"is that the
order in which the operations are to be performed is completely
determined by the positions of the operators and operands in the
expression. Hence, parentheses are not required while writing
expressions in Polish notation. Let us now discuss each of them.
While writing an arithmetic expression, the operator symbol is
usually placed between two operands. For example,
A+ B"C
A"B-C
A+B/C-D
A$B+C
This way of representing arithmetic expressions is called
notation. While evaluating an infix expression usually the
following operator precedence is used:
Highest priority: Exponentiation ( s)
- Next highest priority: Multiplication ( ) and Division (I)
Lowest priority: Addition ( + ) and Subtraction ( - )
If we wish to override these priorities we can do so by using a pair
of parentheses as shown below.
(A+B}C
A(B-C)
(A+B)/(C-D)
The expressions within a pair of parentheses are always evaluated
earlier than other operations.
In prefix notation_the __ the .. For
example, consider an arithmetic expression expressed m infix
notation as shown below:
A+B
This expression in prefix form would be represented as follows:
+AB
The same expression in postfix form would be represented as
follows:
AB+
In notation, the followsJ!le
The prefix and postfix expressions have three features:
_ The operands maintain the same order as in the equivalent infix
expression .
Parentheses are not needed to designate the expression
unambiguously.
- the priority of the

Infix To Prefix Conversion
Let us now see a program that would accept an expression in infix
form and convert it to a prefix form.
Data Structures Through C++ 1811-...- --=-__
#include <iostream.h>
#include <string.h>
#include <ctype.h>
canst intMAX =50;
..
s =str;
strrev (s) ;
I =strien ( s ) ;
target .... I ='\0' ;
t =target .... ( 1- 1) ;
class infix
{
private:
/Iadds operator tothe stack
void infix :: push (charc)
{
char targetlMAX]. stacklMAXJ ;
char s, t;
inttop, I;
if(top==MAX-1)
cout 'Stack isfull\n' ;
else .
{
public:
top- ;
stack[tap] =c ;
infix( ) ;
.void setexpr ( char 'str) ;
void push ( char c ) ;
char pop() ;
void convert( ) ;
int priority ( char c) ;
void show( ) :
};
/Iinitialises data member
infix :: infix( )
{
top =-1 ;
strcpy ( target, .. ) ;
strcpy ( stack, ,. ) :
1=0 ;
}
1/ reverses the given expression
void infix :: setexpr ( char 'str)
{
J '
II pops an operator from the stack
char infix :: poP()
{
if (top =-1 )
{
cout Stack isempty\n' ;
return -1 ;
}
else
{
char item =stack[topJ ;
top-- ;
return item;
}
/I converts the infix expr. toprefix form
void infix :: convert()
{
I
I I
I I
I .
l
opr =pop();
while ( ( opr ) != ')'}
{
}
t=opr;
t- .
I
opr =pop u:
push (opr);
push (s);
if( s == 'n
{
}
else
push (s);
s++ .,
}
~ Chapter 6: Stacks
Data Struaures Through C++
5++
,
continue;
}
if ( isdigit ( s ) II isalpha ( s) )
{
while ( isdigit ( s ) II isalpha ( s) }
{
'=5;
s++ ;
t- .
,
if ( 5 = ' ,II *s== '\t' )
{
while (5)
{
~ I I - - - - ~ - - ; : ; - - - ~ - -
s++;
t++ .
I
}
char opr =pop{ ) ;
"t =opr ~
t- ;
if (c == '$')
return 3:
if ( c== '''II c== 'f \I c= '%' )
. return 2;
while (top!=-1 )
{
II retums the priority of the operator
int infix ::priority ( char c)
{
charopr :
if ( 5 = '.. lIs == '+' lIs == 't II
{ "s= '%' 115 = '.' 115 == '$' )
if( top !=-1)
{
opr =poP(};
rile ( priority ( opr ) >priority ( 5 ) }
t =opr;
t- ;
opr= poP();
}
}
if ( s == '}')
{
push (5) ;
s++ :
EDI Data Structures Through C++
else
{
if (c == '+'" C=='.')
return 1;
else
return 0;
II the prefIX form of given'expr.
void infIX :: show( )
. {
cout << -t ;
t++ .
,
}
void main()
{
char expr(MAXJ ;
infix q;
cout inEnter an expression inInfix form: .
cin.getline ( expr, MAX) ;
q.setexpr{ expr) ;
q.convert( ) ;
coul "The Prefix expression is: ;
q.show() ;
}
Output:
Enter an expression inInfix form: 4 $2 3- 3+8/41 (1 +1)
Stack isempty .
The Prefix expression is: +- $ 42331184 +11
In this program we have designed a class caned infh. This class
contains two character arrays target and stack that store the prefix
expression (string) and the operators (that would be pushed onto
the stack) respectively. The two char pointers s and t are used in
the conversion process. The variable top stores the index of the
item at the topmost position in the stack and I stores the length of
the infix expression entered by the user.
During the course of program execution, the user enters an
arithmetic expression as string (consisting of digits, alphabets and
operators). The function setexpr( ) reverses this expression and
stores it in a string pointed to by s. Thus, if the expression entered
by the user is
4$2-3-3+8/4/(1+1)
then on reversing this string s would point to the string
) 1+1 (14/8+3-32$4
The setexpr( ) function also makes the char pointer t to point to (I
memory location in the target string.
Next the function co vert( ) gets called. This is the function in
which the given infix expression gets converted to prefix
expression. In this function, we are scanning every character of the
string pointed to by s in a while loop. Following steps are
performed depending on the type of character scanned:
(a) If the character scanned happens to be a space then that
character is skipped.
(b) If character scanned is a digit or an alphabet, it is added to the
target string at a position pointed to by t,
(c) If the character scanned is a closing parentheses then it is
added to the stack by calling the pnsh( ) function.
(d) If the character scanned happens to be an-operator, then firstly
the topmost element from the stack is retrieved. Then, through
I
I
j
,
~
I I
. I
32!
i
I'
I
I
I
1
l
I
I \
11 1
1
]1
I I
l
'
1 I
I I
I I
) I
11
I)
I I
I I
J)
I)
J I
I I
ession
..
Infix Expression: 4 S 2 3 - 3 + 8 /4 / ( 1+ I )
Reversed Infix Ex ression: I + 1 /4/ 8 + 3 - 3 2 S 4
Char. scanned Stack Prefix Expression
Let us now see a program that converts an arithmetic expr
given in an infix formto a postfix form,
J
, !
+
/ / +
4 I 4+
rJ
/ / / 4+
8 / / 84+
+ + 1184+
3 + 31184+
+ - 31184+
3 + - 33//84+
+. - 33//84+
2
+ - -
2331184+
S +-S 2331184+
4 +-S 42331184+
Em + --$4233//84+
Table 62. Conversion of Infix to Prefix form.
Infix To Postfix Conversion
I \
\
Data Structures Through C++ 320 11'-- ---:;;...__
a while loop, the priorities of the character scanned (i.e. *s)
and the character popped opr are compared. Following steps
are now performed as per the precedence rule.
(i) If priority of opr is higher than the character scanned,
then opr gets added to the target string.
(ii) If pr has lower or the same priority thanthe character
scanned, then the loop gets terminated. opr gets pushed
back to the stack. Then, the character scanned is also
pushed to the stack.
(e) If the character scanned happens to bean opening parentheses,
then the operators entered into the stack are retrieved through
a loop. The loop continues till it does not encounter a closing
parenthesis. The operators popped, are added to the target
string.
In the convert( ) function we have called functions like push( ),
pope ) and priority( ). The pusb( ) function adds a character to the
stack, whereas the pop( ) function removes the topmost item from
the stack.
The priority( ) function returns the priority of operators used in the
infix expression. The exponentiation operation represented by $
has got the highest precedence. Addition and subtraction has got
lower precedence. The function actually returns integers like 3 for
$, 2 for or I, 1 for + and - and 0 for any other character.
The while loop in the convertf ) gets terminated if the string s is
exhausted. But , then some operators are still there in the stack,
which should get added to the prefix. string. This job is done once
the control reaches outside the wbile loop in the convert( )
function. Lastly, the converted expression is displayed using the
show( ) function.
The steps performed in the conversion of a sample infix expression
4 $ 2 3 3 + 8 / 4 / ( 1 + 1 ) to a prefix expression are shown in
Table 6-2.
#include <iostream.h>
#include <string.h>
#include <ctype.h>
const intMAX =50;
class infix
{
private :
char target[MAX], stack[MAX) ;
char s. t ;
inttop;
public :
infix( ) ;
void setexpr ( char str) ;
void push ( char c) ;
char pop() ;
void convert( ) ;
intpriority ( char c ) :
void show( ) ;
} ;
Data Structures Through c ~ +
, J
I
s =str:
1/ adds an operator tothe stack
void infix :: push ( char c)
{
if ( top == MAX )
cout "Stack isfull\n" :
else
{
top++ ;
staekltop] =c ;
}
/I pops an operator from the stack
char infix :: pop( )
{
if{ top == 1 )
{
cout 'Stack isernpty\n" ;
return -1 ;
}
else
(
c
1/ initialises data members
infix :: infix( )
{
top =-1 ;
strcpy ( target, ".) ;
strcpy ( stackI ) :
t =target;
5 = ;
1/ sets s topoint togiven expr.
void inftx :: setexpr ( char str )
(
I.
char item =stackltop] ;
top- ;
return item;
}
/I converts the given expr. from infIX topostfix form
void infix :: convert( )
(
while ('s)
{
if ( 's == I I \I "s== '\f )
{
. Data Structures Through C++
I , - - ---_---:::........--
s++ .
I
continue ;
}
if ( isdigit ( 5 ) Uisalpha ( 5 ) )
{
while ( isdigit ( 5 ) " isalpha ( s ) )
{
t =5;
5++ ;
t++ ;
}
}
if ( 's == ')')
{
opr=poP();
while ( ( opr ) != '(')
{
t:: opr;
t++ ;
opr = pop{);
}
s++ ;
iI
, .
if( s == '(')
{
}
push (s) ;
s++ ;
while (top !=-1 )
{
charopr;
if (5 == 'et " s ::= '+' ,,s == 'f lIs == '%' lIs == '.'Us == '$')
{
if(top!=-1)
{
opr =pop();
white ( priority ( opr ) >= priority ( s ) )
{
t =opr;
t++ ;
opr =pop();
}
push ( opr) ;
push (s);
}
else
push (s) ;
s++ ;
char opr :: pop( ) ;
t:: opr;
t++ ;
}
t :: '\0' ;
/Ireturns the priority of an operator
intinfix :: priority ( char c )
{
if(c=='$')
return 3;
if ( c== '81 II c == 't II c = '%' )
return 2;
else
{
if ( c == '+'11 c == '.' )
return 1 ;
else
return 0 ;
" ,
I
I
I
Chapter 6: Stacks
Data Structures Through C++ 1 6 1 1 ~ -=-__
}
1/ displays the postfix farm of given expr.
void infix :: show( )
{
cout target ;
}
void main()
{
char expr[MAX] ;
infixq;
cout "'nEnter an expression inInfix form: " ;
cin.gelline (expr, MAX) ;
q.setexpr ( expr ) ;
q.convert{ J ;
cout "The Postfix expression is: " ;
q.show(} ;
}
Output:
Enler an expression inInfix form: 4 $ 2- 3 3 +8/4 1( 1+1)
Stack isempty .
The Postfix expression is: 42$3-3-84/11+1+
This program too contains a class called inflx. The data members
target and stack, are used to store the postfix string and to
maintain the stack respectively. The char pointers sand t are used
to store intermediate results while converting an infix expression to
a postfix form. The variable top points to the top of the stack.
During the course of program execution, the user enters an
arithmetic expression (consisting of digits, alphabets and
operators). The function setexpr( ) assigns the base address of the
string to char pointer s. Note that, here we have not reversed the
original infix expression, as we did in case of infix to prefix
conversion.
Next, the function convert( ) gets called. This function converts the
given infix expression to postfix expression. As done in previous
program of infix to prefix conversion, here too we have scanned
every character of the string in a while loop till we do not reach the
end of string pointed to by s. Following steps are performed
depending on the type of character scanned.
(a) If the character scanned happens to be a space then that
character is skipped.
(b) If character scanned is a digit or an alphabet, it is added to the
target string pointed to by t.
(c) If the character scanned is a closing parentheses then it is
added to the stack by calling p sh() function.
(d) If the character scanned happens to be an operator, then firstly,
the topmost element from the stack is retrieved. Through a
while loop, the priorities of the character scanned (i.e.*s) and
the character popped opr are compared. Then following steps
are performed as per the precedence rule.
~ If opr has higher or same priority as the character
scanned, then opr is added to the target string.
(ii) If opr has lower precedence than the character scanned,
then the loop is terminated. opr is pushed back to the
stack. Then, the character scanned (*s) is also added to .
the stack.
(e) If the character scanned happens to be an opening parentheses,
then the operators present in the stack are retrieved through a
loop. The loop continues till it does not encounter a closing
parenthese, The operators popped, are added to the target
string pointed to by 1.
i
i
I I
I
. I
I
I
Data Structures Through C++
328 11'-- -----..::::.-.-_
In the convert( ) function we have called functions like push( ),
pop( ), priority( ). The working of these functions is same as
discussed in previous program.
The while loop in the convert( ) gets terminated if the string 5 is
exhausted. But, then some operators are still there in the stack,
which should get added to the prefix string. This job would be done
in the show( ) function. At first look the prefix form of an infix
expression appears to be a mirror image of the postfix form. But,
this is not true. If observed carefully, there is a difference between
a prefix and postfix form.
The steps performed in the conversion ofa sample infix expression
4 $ 2 * 3 - 3' + 8 / 4 / ( I + 1 ) to a postfix expression are shown in
Table 6-3.
Infix Expression: 4 $ 2 3 - 3 + 8 /41 ( 1+ 1 )
Char Seanned Stack Contents Postfix Expression
4 Empty 4
s s 4
2 s 42
42$
3 42$3
.
-
42$3-
3

42$3
8
3
+ + 42S3
83.
8 + 42S3
8
3 8
/ +/ 42S3
8
3 - 8
4 +/ 42S3
83-84
/ +/ 42$3
83-841
( + / ( 42S3
83-841
1 +11. 42S3 3- 84/1
+ +/ {+ 42S)-3-84/1
I +/ (+ 42S383-84/11
) +/ 42S)-3-84/11+
Empty 42S)-3-84/11+/+
Table 63. Conversion of Infix to Postfix form.
Postfix To Prefix Conversion
Let us now see a program that converts an expression in postfix
form to a prefix form,
#include <iostream.h>
Data Structures Through C++
330 111- --.;:""-_
#include <string.h>
const intMAX =50 :
class postfix
{
private:
char stacklMAX)[MAX). target[MAX] ;
char temp1 [2], temp2[2] ;
char,str1[Ml\X], str2[MAX1. str3(Ml\X] ;
int i, top;
public:
,
void postfix :: push ( char str)
{
if ( top == MAX 1)
cout endl 'Stack isfull" ;
else
{
top++ ;
strcpy (stack[top], str) ;
)
/I pops an element from thestack
void postfix ::pop ( char -a)
{
strcpy ( target. c) ;
postflX(} ;
void setexpr (charc) ;
void push ( char str) ;
void pop ( char *a) :
void convert( ) ;
void show( ) ;
} ;
/I initialises data members
postfix ::postfIX( )
{
i=O;
top.:: -1 ;
strcpy ( target, ) ;
}
/I copies given expr. totarget string
void postfIX :: setexpr ( char *c)
{
}
/I adds an operator tothe stack
if ( top == -1 )
cout endl 'Stack isempty"' ;
else
{
strcpy (a, stack[top] ) ;
top-;
}
}
/I converts given expr. to prefix form
void postfix :: convert( )
{
while ( targetli] !=\0' )
{
IIskip whitespace, if any
if ( targetp] == I 1
j++;
if(target[i] = '%' II target[i] =,.. II
targetPI == ''11 targetPl == '+' II
t a r g e t ~ ] ==" II target[i] ='$' )
pop (str2);
pop (str3);
temp1 [OJ =targetp] :
temp1[1] ='\0' ;
strcpy ( str1, temp1 ) :
strcat ( strt, str3 ) ;
strcat ( strt, str2 ) ;
push ( str1 ) ;
Data Structures Through C++
coot "The PrefIX expression is: ;
q.show() ;
}
else
{
temp1[OJ =t a r g e t ~ ! ;
temp1[1! ='\0' ;
.slrcpy (temp2, temp1 ) ;
push ( lemp2 ) ;
i++ ;
" displays the prefix form of expr.
void postfix :: show( )
{
char "temp =stack[O] ;
while ( "temp )
{
cout "ternp . ;
temp++ ;
void main()
{
char expr{MAX] ;
coot "\nEnter an expression inPostfix form: ;
cin.get/ine ( expr, MAX) ;
postfix q;
q.setexpr ( expr) ;
q.convert( ) ;
~ ..
Output:
Enter an expression inPostfix form: 42$ 3 384 /1 1+1+
The Prefix expression is: + $ 4233/18 4+ 11
In this program the class postfu contains character arrays like
tempI, temp2, strl, str2, str3 to store the intermediate results.
The character arrays stack and target are used to maintain the
stack and to store the final string in the prefix form respectively.
In the convert( ) function the string containing expression in
postfix form (pointed to by s) is scanned through a while loop tin
the string is not exhausted. Following steps are performed
depending on the type of character scanned.
(a) If the character scanned is a space then that character is
skipped.
(b) If the character scanned contains a digit or an alphabet, it is
pushed to.the stack by calling pusb( ) function.
(c) If the character scanned contains an operator, then the topmost
two elements are popped from the stack. These two elements
are then stored in the array tempI. A temporary string templ
containing the operator and the two operands is formed. This
temporary string is then pushed on the stack.
The postfix form that is converted to prefix form is stored at the Olll
position in the stack. Finally, the sbow( ) function displays the
prefix form. The steps performed in the conversion of a sample
postfix expression 4 2 $ 3 * 3 - 8 4 I I I + I + to its equivalent
prefix expression is demonstrated in Table 6-4.
Chapter6: Stacks
------------11335
DataStructures Through C++ 334 11 --=-__
const intMAX =50 ;
Postfix Expression: 4 2 S 3 3 - 8 4 I 1 1+1+
Cb r. Scaaned Stack Contents
' 4 4
2 42
S $42
3 $423
'"
$ 4"23
3 S 4 2 3,3
. -"'$4233
8 - S 4233,8
4 -S423384
I -S4233/84
1 - '"$ 4 2 3 3,18 4 1
1 '" S 4 2 3 3, I 8 4, I, 1
+ - '" S 4 2 3 3, I 8 4 + I 1
I - S 4 2 3 3, II 8 4 + 1 1
+ +-$42331184+11
Table 64. Conversion of Postfixto Prefixform.
class postfix
{
private:
char stack[MAXl[MAX], target[MAX] ;
char temp1 [2}. temp2[2} ;
char str1[MAX], str2[MAX1, str3[MAX1 ;
inl i. top;
public:
postfix () ;
void setexpr ( char c ) ;
void push ( char str ) ;
void pop ( char a) ;
void convert( ) ;
void show( } ;
} ;
II initialises data member
postfix :: postfix( )
{
i= 0;
top s-t :
strcpy ( target, ) ;
}
Postfix To Infix Conversion
Let us now see a program to convert an expression in POStfiX form
to an infixform,
/Icopies given expression totarget string
void postfix :: setexpr ( charc )
{
strcpy ( target, c) ;
}
#include <:iostream.h>
#include <string.h>
/I adds an expr. tothe stack
void postfix :: push ( char str)
{
Data Structures Through C++ 336 11'--- :::.....-_
}
cout endl "Stack isfull" ;
else
{
top++ ;
strcpy ( stack[topj. str) ;
}
II pops an expr. from the stack
void postfIX:: pop ( char -a)
{
if ( top == -1 )
cout endl "Stack isempty" ;
else
{
strcpy (a, stack[top] ) ;
top- :
}
/Iconverts given expr. toinfix form
void postfix :: convert( )
{
while ( )
{
Ilskip whitespace. if any
if( == ' ,)
i++ ;
if ( target[i] == '%' IItargetpJ == '.. II
targetPl == '.' IItargetliJ == '+'11
targetPl == 't II targetpl == '$' )
{
pop ( str2) ;
pop ( str3 ) ;
temp1 [OJ =targetPI ;
temp1l1] ='\0'; .
strcpy ( strt, str3 ) ;
strcat ( str1 . temp1 ) ;
strcat ( str1 , str2 ) ;
push ( str1 ) ;
}
else
{
temp1[O) =target[i] ;
temp1[1l ='\0' ;
strcpy ( temp2. temp1 ) ;
push ( ) ;
}
i++ ;
If displays the expression
void postfix::show ( )
{
char at ;
t =stack[O] ;
while (at)
{
cout at ;
t++ ;
}
cout cc endl ;
}
void main()
{
char ;
cout "\nEnter an expression inPostfix form: " ;
cin.getline ( expr, MAX) ;
pOStfIX q;
q.setexpr ( expr);
q.convert( ) ;
DataStructures Through C++
338 IIL..-. - - - - : ~ -
cout -mThe I n ~ x expression is: ;
q.show(} ;
Output:
Enter an expression in Postfix fonn: 42$ 3 384/1 1+- / +-
The Infix expression is: 4$ 2 3- 3+ 8/4 /1 + 1
This program is similar to the one discussed in previous section
'Postfix To Prefix Conversion', except for a small difference in the
convert( ) function. Since, this program is to convert a postfix
form to an infix form, the operator would get placed between the
two operands. The steps that are performed in the convertf )
function are given below:
(a) The while loop runs as long as the string s is not exhausted.
(b) If the character scanned happens to be a space then that
character is skipped.
(c) If the character scanned is a digit or an alphabet. it is added to
the stack by calling push() function.
(d) If the character scanned is an operator, then the topmost two
elements (operands) are popped from the stack. A temporary
string containing an operand-operator-operand is formed. This
temporary string is then pushed on the stack.
The postfix form converted to an infix form, is stored at the Olh
position in the stack. Finally, the show( ) function displays the
infix form. The steps carried out in converting a sample postfix
expression to an infix expression are demonstrated in Table 6-5.
Postfix Expression: 4 2 S 3 3 - 8 4/1 1'+ / +
Char. Scanned Stack Contents
4 4
2 4 2
S 4$2
3 4$ 2 3
4S2-3
3 4 s2'" 3.3
-
4$2-3-3
8 4 S 2'" 3 - 3, 8
4 4 S2 3 - 3, 8.4
I 4 S2 3 - 3. 8 /4
1 4 $ 2 3 - 3 8 /4. 1
1 4$2'"3-38/411
+ 4 S 2 '" 3 - 3. 8 /4 , I + I
/ 4S2-3-38/4/1+1
+ 4$2'"3-3+8/4/1 + I
Table 65. Conversion of Postfix to Infi)( form.
Evaluation Of Postfix Expression
The virtue of postfix notation is that it enables easy evaluation of
expressions. To begin with, the need for parentheses is eliminated.
Secondly, the priority' of the operators is no longer relevant. The
Data Structures Through C++
340 111....- --:::...-_
s =str:
expression can be evaluated by making a left to right scan. stacking
operands. and evaluating operators using as operands the correct
elements from the stack and finally placing the result onto the
stack. This evaluation is much simpler than attempting a direct
evaluation of infix notation. Let us now see a program to evaluate a
postfix expression.
/I sets s to point tothe given expr.
voidpostfix :: setexpr (charstr)
{
}
#include <iostream.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
const int MAX =50 ;
/I adds digit tothe stack
voidpostfix :: push ( int item)
{
if ( top == MAX - 1)
cout endl 'Stack isfun" :
else
{
class postfix
{
private :
top++ ;
stack[top) =item;
}
intstacl<[MAX] ;
inttop, nn ;
cnar rs:
public :
/Ipops digit from the stack
intpostfix :: pop{ )
{ .
if (top= -1)
{
top=1;
postfix( ) ;
void setexpr ( char str ):
void push ( int item);
intpop() ;
void calculate( ) ;
void show( ) ;
};
1/ initialises data members
postfix :: postfix( )
{
}
cout endl 'Stack isempty" ;
return NULL ;
}
intdata =stacl<ltop] ;
top-;
return data ;
}
1/ evaluates the postfix expression
void postfix :: calculate( )
{
intn1, n2, n3;
while (s)
{
II skip wtlitespace, ifany
if ( "s== ' '''5== '\I' )
{
s++ ;
continue ;
/I if digit isencountered
if ( isdigil ( s ))
{
nn =s -'0';
push (nn);
)
else
{
II if operator isencountered
n1 =pop{):
n2 =pop();
switch (s)
{
case '+' :
n3 =02+n1 ;
break;
case '.':
n3 = n2 - n1;
break;
case 'f :
n3 =n21 n1 ;
break;
case ,.. :
n3 =n2. n1 ;
break;
case'%' :
n3= n2 %n1 ;
Data Structures Through C++
break;
case '$':
03=pow ( 02, n1 ) ;
break;
default :
cout <:< Unknown operator" ;
exit{ 1) ;
}
push (n3) ;
s++ ;
)
}
II displays the result
void postfix :: show()
{
nn=pop ();
cout "Result is: <<: nn ;
}
void maln()
{
char e x p ~ M A X ] :
cout c "\nEnter POStfIX expression tobe evaluated: ;
tin.getJine ( expr, MAX) ;
postfIX q;
q.setexpr (expr) :
q.calculate( ) ;
q.show() ;
Data Structures Through C++ 344 II'--_--:-- ~ _=____
Output:
Enter Postfix expression tobeevaluated: 42S3.. 3- 84/1 1+/ +
Result is: 46
In this program the class postfix contains an integer array stack, to
store the intermediate results of the operations and top to store the
position of the topmost element in the stack. The evaluation of the
expression gets performed in the calculate( ) function.
During the course of execution, the user enters an arithmetic
expression in the postfix form. In the calculate( ) function, this
expression would get scanned character by character. If the
character scanned is an operand, then first it is converted to a digit
form (from string form), and then it is pushed onto the stack. If the
character scanned is a blank space, then it is skipped. If the
character scanned is an operator, then the top two elements from
the stack are retrieved. An arithmetic operation is performed
between the two operands. The type of arithmetic operation i.e,
addition, subtraction or multiplication etc. depends on the operator
scanned from the sting s. The result is then pushed back onto the
stack. These steps are repeated as long as the string s is not
exhausted. The sbow( ) function displays the final result. These
steps can be better understood if you go through the evaluation of a
sample postfix expression shown in Table 6-6.
Postfix Expression: 4 2 S 3 3 8 4 I 1 1 +I +

Char. Sanned Stack Contents


4 4
2 ~ 2
s 16
3 16 3
48
3 48,3
.
45
8 45,8
4 45 8 4
I 45,2
1 4 ~ 2 , 1
1 45 2 1, I
+ 4 ~ 2 2
I 45,1
+ 46 (Result)
Table 6-6. Evaluation of Postfixexpression.
Exercise
(A) Fill in the blanks:
DataStructures Through C++

(a) A is a data structure in which addition of new element or
deletion of an existing element always takes place at an end
called
---
. (b) The data structure stack is also called
structure.
(a) Copying contents of one stack to another.
(b) To check whether a string of opening and closing parenthesis
is well formed or not.
(8) Pick up the correct alternative for each of the folIowing
questions:
(e) In
operands.
(d) In
operands.
notation the operators precedes the two
otation the operator follows the two
[OJ Transform the following infixexpressions into their equivalent
POStfIX expressions:
(A-8)*(D/E)
(A+Bl\O)/(E-F}+G
A*(B+D)/E-F*{G+H/K)
(A+B)*(C-O)SE*F
(A+B)*(C$(O-E)+F)/G)$(H-J)
(a) Adding an element to the stack means
(1) Placing an element at the front end
(2) Placing an element at the top
(3) Placing an element at the rear d
(4) None of the above
[EJ Transform the following infix expressions into their equivalent
prefix expressions:
(A-B)*(D/E)
(A+Bl\D)/(E-F)+G
A*(B+O)/E-F*(G+H/K)
(b) Pushing an element to a stack means
(I) Removing anelement from the stack
(2) Searching a given element in the stack
(3) Adding a new element to the stack
(4) Sorting the elements in the stack
[FJ Transform each of the following prefix expression to infix,
+ABC
++A*$BCD/+EF*GHI
+-$ABC*O"EFG
(c) Popping an element from the stack means
(1) Removing an element from the stack.
(2) Searching a given element in the stack
(3) Adding a new element to the stack
(4) Sorting the elements in the stack
fC) Write programs for the
[G) Transform each of the following postfix expression to infix,
ABC+-
AB-C+OEF-+S
ABCDE-+S*EF*-
Data Structures Through C++
148 J I . . . - - - - - - - : : : - ~ - - - - -
CHAPTER
SEVEN
Queues
Await Your Turn
W
hether it is a railway reservation counter, a movie theatre
or print jobs submitted to a network printer there is only
one way to bring order to chaos-form a queue. If you
await your turn patiently there is a more likelihood that you would
get a better service.
Queue is a linear data structure that permits insertion of new
element at one end and deletion of an element at the other end. The
349
Chapter 7: Queues
Data Structures Through c++
350 11 .....:.-...:::..-_
end at which the deletion of an element take place is called front,
and the end at which insertion of a new element can take place is
called re r. The deletion or insertion of elements can take place
onlyat the front or rear end of the list respectively.
The first element that gets added into the queue is the first one to
get removed from the list Hence, queue is also referred to as first-
in-first-out (FIFO) list. The name 'queue' comes from the everyday
use of the term. Consider a queue of people waiting at a bus stop.
Each new person who comes takes his or her place at the end of the
line, and when the bus comes, the people at the front of the line
board first. The first person in the line the first person to leave.
Figure 7-1 gives a pictorial representation ofa queue.
9]
23
1-a LfJ
rear
Figure 7-1. Pictorial representation of a queue.
In Figure 7-1, 34 is the first element and 42 is the last element
added. 1'0 the queue. Similarly, 34 would be the first element to get
removed and 42 would bethe last element to get removed.
Applications of queue as a data structure are even more common
than applications of stacks. While performing tasks on a computer,
it is often necessary to wait one's tum before having access to some
device or process. Within a computer system there may be queues
of tasks waiting for the line printer, or for access to disk storage, or
in a time-sharing system for use of the CPU. Within a single
program, there may be multiple requests to be kept in a queue, or
one task may create other tasks, which must be done in tum by
keeping them in a queue.
Let us now discuss how a queue can be represented in order to use
it in a program.
Representation Of A Queue As An Array
Queue, being a linear data structure can be in various
ways such as arrays and linked lists. Representing a queue as an
array would have the same problem that we discussed in case of
stacks. An may is a data structure that can store a fixed num.her
elements. The size of an array should be fixed before usmg It
Queue, on the other hand keeps on changing as we remove
elements from the front end or add new elements at the rear end.
Declaring an arraywith a maximum size would solve this problem.
The maximum size should be large enough for a queue to expand
or shrink. Figure 7-2 shows the representation of a queue as an
array.
arr[O] arr[1] arr[2J am3] arr[4] arr[S] arr[6] arr[7]
lfl12 I 53 I 61 I 9 I 23 I -a LfJ
front rear
Figure 7-2. Representation of a queueas an array.
Let us now see a program that implements queue as an array.
#include <ioslream.h>
const intMAX =10;
class queue
{
private:
intarr[MAX) ;
DataStructures Through C++
352 II
- - - - - - - - - - - - - - ~ - - = - -
jntfront, rear;
public:
caul "\nQueue is Empty" ;
return NULL;
queue();
void addq ( intitem):
intdelq() :
};
/I initialises data members
queue :: queue{ )
{
}
data =arrlfront] :
arr[front] =0;
if ( front == rear)
front =rear =-1 ;
else
front++ ;
front =-1 ;
rear=-l ;
}
return data;
}
II adds an element to the queue
void queue :: addq ( int item)
{
void main()
{
queue a;
if(rear==MAX-1)
{
cout inQueue isfuJr :
return :
}
rear++ ;
arr[rear] =item;
if (front== 1 )
front =0;
}
II removes an element from the queue
intqueue :: delQ( )
{
intdata;
a.addq ( 23 ) ;
a.addq (9);
a.addq (11) ;
a.addq (-10) ;
a.addq ( 25) ;
a.addq ( 16) ;
a.addq ( 17) ;
a.addq ( 22) ;
a.addq ( 19) ;
a.addq ( 30) ;
a.addq ( 32 ) ;
inti =a.delq( ) ;
cout "\nltemdeleted:' i;
i =a.delq{ ) ;
cout- "\nltem deleted: i ;
if ( front ==-1 )
i =a.delq( ) ;
354 II
'----
DataStructures Through C++
Figure 7-3. Adding an element to a queue.
Here we have designed a class called queue. We have also
declared two data members front and rear to monitor the two ends
of the queue. The initial values of front and rear are set to -1,
which indicate that the queue is empty. To carry out the addition
and deletion operations on the queue we have implemented two
functions within the queue class, namely, addq() and delq().
While adding a new element to the queue, first it would be
ascertained whether such an addition is possible or not. Since the
array indexing begins with 0 the maximum number of elements
that can. be stored in the queue are MAX - I. If these many
elements are already present in the queue then it is reported to be
full. If the element can be added to the queue then the value .ofthe
variable rear is incremented and the new item is stored in the
array. The addition of an element to the queue has been illustrated
in Figure 7-3.
Output:
Queue isfull
Item deleted: 23
Item deleted: 9
Item deleted: 11
Figure 7-4. Representation of queue after deleting an element.
~ .
front rear
After Deletion Before Deletion
J 23 I 9 I 11 I -101 25 J
frtnt rIar
If the item being added to the queue is the first element (i.e. if the
variable front has a value -I) then as soon as the item is added to
the queue front is set to 0 indicating that the queue is no longer
empty.
Let us now see how the delq( ) function works. Before deleting an
element from the queue it is first ascertained whether there are any
elements available for deletion. If not, then the queue is reported as
empty. Otherwise, an element is deleted form rr(front}. The
deletion of an element is illustrated in Figure 7-4.
Imagine a case where we add 5 elements to the queue. Value of
rear would now be 4. Suppose we have not deleted any elements
from the queue, then at this stage the value of front would be O.
Now suppose we go on deleting elements from the queue. When
the fifth element is deleted the queue would fall empty. To make
sure that another attempt to delete should be met with an 'empty
queue' message, in such a case front and rear both are reset to -I
to indicate emptiness of the queue.
But this program has got some limitations. Suppose we go on
adding elements to the queue till the entire array gets fined. At this
stage the value of rear would be MAX - I. Now if we delete 5
elements from the queue, :: the end of these deletions the value of
front would be 5. If now we attempt to add a new element to the
,
After Adding
I 23 I 9 J 11 I -10 I 25 I
tr!nt rlar
coet "mltem deleted: i :
Before Adding
~
front r ar
}
Data Structures Through c++ 356
111.- ..:::.....-._
queue then it would be reported as full even though in reality the
first five slots of the queue are empty. To overcome this situation
we can implement a queue as a circular queue, which would be
discussed later in this chapter.
Let us now see a program that implements the queue as a linked
list
#include <iostream.h>
Representation or A Queue As A Linked-List
Queue can also be represented using a linked list. As discussed
earlier, linked lists do not have any restrictions on the number of
elements it can hold. Space for the elements in a linked list is
allocated dynamically, hence it can grow as long as there is enough
memory available for dynamic allocation. The item in the queue
represented as a linked list would be a structure as shown below:
class queue
{
private :
struct node
{
intdata ;
node -link ;
} -front, -rear:
struct node
{
public :
}
<dataType> data;
node -'ink;
where dataType represents the type of data such as an Int, float,
char, etc. Figure 7-5 shows the representation of a queue as a
linked list.
front =rear =NULL;
queue();
void addq ( int item) ;
int delq( ) ;
-queue();
If adds an element tothe queue
void queue :: addq ( int item)
{
} ;
/I initialises data member
queue :: queue( )
{
}
rear
p03-...
S
_3 .-.
front
node -temp ;
Figure 7-5. Representation of a queue as a linked Jist. temp =new node ;
if ( temp == NULL)
cout "\nQueue is full- ;
temp .> data =item ;
temp ->link =NULL;
if ( front ._-NULL )
{
rear =front =temp ;
return ;
}
DataStructures Through c++
node "temp;
while ( front !=NULL)
{
temp =front;
front =front ->link;
delete temp ;
}
rear ->link =temp:
rear =rear .> link;
}
/I remo es an element from the queue
intqueue :: delq( )
{
if ( front == NULL)
{
cout "'nQueue isempty" ;
return NULL;
}
node "temp;
intitem;
item =front .> data ;
temp =front;
front =front .>link ;
delete temp ;
return nem;
}
II deallocales memory
queue :: -queue( )
{
if ( fronl =NULL)
return ;
void main()
{
queue a:
a.addq (11) ;
a.addq ( -8) ;
a.addq ( 23 ) ;
a.addq ( 19) ;
a.addq ( 15) ;
a.addq ( 16) ;
a.addq ( 28 ) ;
inti =a.delq( ) ;
cout "\!lItem extracted: " i ;
i =a.delq() ;
cout "\nltemextracted: " <:< i :
i =a.delq( ) ;
cout cc "Vlltem extracted: " cc i ;
}
Output:
Itern extracted: 11
Item extracted: -a
Itemextracted: 23
Data Structures Through c++
360 II
-------------------=:::.-_-
In this program the class queue contains two data members front
and rear, both pointers to the structure . To begin with, the
queue is empty hence both front and rear are set to NULL.
The ddq(} function adds a new element at the rear end of the list.
If the element added is the first element, then both froot and rear
are made to point to the new node. However, if the element added
is not the first element then only re r is made to point to the new
node, whereas front continues to point to the first node in the list.
The delq( } function removes an element from the list which is at
the front end of the list. Removal of an element from the list
actually deletes the node to which front is pointing. After deletion
of a node, froot is made to point to the next node that comes in the
list, whereas rear continues to point to the last node in the list.
When the program terminates the object a dies. As a result the
destructor is called. In the destructor the memory allocated for the
existing nodes in the list is deallocated.
have reached the end of the array the queue would not be reported
as full. The queue would be reported as full only when all the slots
in the array stand occupied. Figure 7-6 shows the pictorial
representation of a circular queue.
front
"Circular Queues
The queue that we implemented using an array suffers from one
limitation. In that implementation there is a possibility that the
queue is reported as full (since rear has reached the end of the
"array), even though in actuality there might be empty slots at the
beginning of the queue. To overcome this limitation we can
implement the queue as a circular queue. Here as we go on adding
elements to the queue and reach the end of the array, the next
element is stored in the first slot of the array (provided it is free).
More clearly, suppose an array arr of 0 elements is used to
implement a circular queue. Now if we go on adding elements to
the queue we may reach arr[ -I) . We cannot add any more
elements to the queue since we have reached the end of the array.
Instead of reporting the queue as full, if some elements in the
queue have been deleted then there might be empty slots at the
beginning of the queue. In such a case these slots would be filled
by new elements being added to the queue. In short just because we
Figure 7-6. Pictorial representation ofa circular queue.
Let us now see a program that performs the addition and deletion
operation on a circular queue.
#include <iostream.h>
const int MAX =10:
class queue
{
private:
intarr! MAX l ;
int front, rear;
public:
Chapter 7: Queues
--------------,11363
Data Structures Through c++
362 J[ - . : : : . : : = - = . : . : - = = . : . : . . . . : . . : . ~ ~ . . : . - .
}
/I initialises data member
queue :: queue( )
{
/I adds'an element tothequeue
void queue ::addq ( intitem)
{ -
ff{ ( rear == ~ - 1&& front == 0) ,,( rear +1= front ) }
{
-caut "\nQueue is full- :
return ;
front =-1 ;
rear =-1 ;
if ( front =; MAX 1)
front =0;
else
front++ ;
}
if ( front = -1 )
{
cout "\nQueue isempty" ;
return NULL;
data =arr{front] ;
arr{front] = 0 ;
if ( front =rear)
{.
}
else
{
cout endl ;
for ( inti =0: i < MAX ; i++ )
cout arr[i] . ":
rout endl ;
}
return data;
/I displays element inaqueue
vold queue :: dispfay{ )
{
}
queue() ;
void addq ( intitem) ;
int delq(};
void display( ) ;
front - rear =-1 .
for (inti ='0; i <'MAX; i++)
arrIil =0;
if{rear==MAX1 )
rear =0;
else
rear++ ;
arr{reC!!'l =item;
if ( front = -1 )
front =0;
};
}
}
II removes an element from the queue
int queue ::delq( )
{ .
intdata ;
void main{)
{
queue a;
Chapter 7: Queues
DataStructures Through C++
364 I [ - - - - - - - ; : ; - : - : : : : - - ~ - -
Output:
Elements In the circular queue:
142213.025 00000
Item deleted: 14
}
a.addq ( 14) ;
a.addq ( 22 ) ;
a.addq ( 13);
a.addq ( -6) ;
a.addq ( 25 ) ;
~ "\nBements in the circular queue: " .
a.dlsplay( } ; ,
inti =a.delq( ) ;
cout "!tem deleted: ;;
i =a.delq( ) ;
cout "\nltem deleted: " i ;
~ t inElements inthe circular queue after deletion' .
a.dlsplay( ) ; . I
a.addq ( 21 ) ;
a.addq ( 17) ;
a.addq ( 18) ;
a.addq (9);
a.addq ( 20 ) ;
~ t "Elements inthe circular queue after addition. .
a.dlsplay( ) ; . I
a.addQ ( 32) ;
~ "Elements inthecircular queue after addition' .
adlSplay( ) ; . ,
Itemdeleted: 22
Elements inthe circular queue after deletion:
o0 13-625 00000
Elements inthe circular queue after addition:
0013 -625211'718920
Bements in the circular queue after addition:
32013-625211718920
Here the class que e contains an array arr to store the elements of
the circular queue. The member functions addq( ) and derq( ) add
and remove the elements from the queue respectively. The function
display( ) displays the existing elements of the queue. The initial
values of front and rear are set to -1, which indicates that the
queue is empty.
In m inC ). first we have called the addq( ) function 5 times to
insert elements in the circular queue. In this function. following
cases are considered before adding an element to the queue.
(a) First we have checked whether or not the array is full. The
message 'Queue is full' gets displayed if front and rear are in
djacent locations with rear following the front.
(b) If the value of front is -1 then it indicates that the queue is
empty and the element to be added would be the first element
in the queue. The values of fro t and rear in such case are
set to 0 and the new element gets placed at the Olb position.
(c) It may also happen that some of the positions at the front end
of the array arc vacant. This happens if we have deleted some
elements from the queue, when the value of rear is MAX - 1
and the value of front is greater than O. In such a case the
value of rear is set to 0 and the element to beadded is added
at this position.
(d) The element is added at the rear position in case the value of
front is either equal to or greater than 0 and the value of rear
is less than MAX - 1.
Chapter 7: Queues

Data Structures Through C++
Thus. after adding 5 elements the value of front and rear become
o and 4 respectively. The display( ) function displays the elements
in the queue, Figure 7-7 shows the pictorial representation of a
circular queue after adding 5 elements
front
rear
FIgure 7-7. Pictorialrepresentation of circularqueueafter addition
of 5 elements.
Next we have called delq( ) function twice to remove 2 elements
from the queue. The following conditions are checked while
deleting an element.
(a) First we have checked whether or not the queue is empty. The
value of front in our case is 4. hence an element at the front
position would get removed.
(b) Next. we have checked if the value offi t has become equal
to rear. If it has. then the element we wish to remove is the
only element of the queue. On removal of this element the
queue would become empty and hence the values of front and
rear are set to -1.
On deleting an element from the queue the value of front is set to 0
if it is equal to MAX - 1. Otherwise front is simply increment by
1. Figure 7-8 shows the pictorial representation of a circular queue
after deleting two elements from the queue.
rear
Figure 7-8. Pictorial representation a circularqueueafterde/etlng
. two elements fromthequeue.
Further calls to addq( ) function adds elements 17. 18. 9. and
20 to the queue. The value of front and rear at this stage
2 and MAX - I respectively. One more call to addq( ) function
changes the value of rear from MAX - I to 0 and the element gets
added at the Olb position.
Deque
The word deque is a short form of double-ended queue and. defines
a data structure in which items can be added or deleted at.elther
front or rear end, but no changes can bemade elsewhere In list.
Thus a deque is a generalization of both a stackand a queue. Figure
7-9 shows the representation of a deque.
front =rear =-1 ;
for ( inti =0; i <MAX ; i++ )
arrU] =0;
1/ adds an element atthe beginning ofadeque
void dQue::addQatbeg ( intitem)
{
if (front =0&&rear= MAX-1 )
{ cout "\nDeque isfull" endl ;
return ;
Chapter 7: Queues
-----------1(369
rear
Data Structures Through C++
+-Insertlon
.........._'--..... ..........
Deletion
Let us pow see a programthat implements a deque using an array.
Figure 7-9. Representation ofa deque.
368 IIL.-.
}
#include <iostream.h>
oonst iotMAX =10;
class-dque
{ --
private:
intarr(MAX] ;
intfront rear ;
public:
dque() ;
void addqatbeg ( intitem) ;
void addqatend ( intitem ) ;
intdelQatbeg( ) ;
intdelQatend( ) ;
void display( ) ;
;
};
1/ initiaUses data members
dque ::dque( )
if (front=-1 )
{
front =rear =0;
arr[front] =item ;
return ;
}
if ( rear !=MAX 1)
{
intc =count( ) ;
intk=rear +1;
for ( inti =1; i <= c ; i++ )
{
arr['K] =arr['K - 1] ;
k-;
}
arr[k] =item;
front =k;
rear++ ;
}
else
{
front-;
intitem ;; ;
arr[front] =a;
if ( front = rear)
front =rear -1 ;
else
front++ ;
Chapter 7: Queues
II removes an element from the front end ofdeque
int dque :: delqatbeg( )
{
if ( front == -1)
{ cout inDeque isemptf endl ;
return 0;

Data Structures Through c++
arr(front] =item ;
}
}
if ( front = -1 )
{ .
rear =front =0;
arr[rear] =item;
return ;
:370 JI
"'-----------------.....:::.._-
/I adds an element at the end ofadeque
voiddque :: addqatend ( int item)
{
if ( front = 0 && rear == MAX - 1)
{
cout inDeque isfull" endl ;
return ;
}
return item ;
intitem;;arr{rear] ;
arr[rear) =0;
rear- ;
if ( rear ==-1 )
front =-1 ;
return item;
/I removes an element from the rear end of deque
in!dque :: delqatend( )
{
if ( front = -1 )
{ cout inDeque isemptf endI ;
return 0;
k=j:
if(k==MAX-1)
arrlk) =0;
else
arrlk] ;; arrli +1J;
}
rear- ;
front-;
int k=front - 1;
for ( inti =front - 1; i <rear ; i++ )
{
if ( rear == MAX 1)
{
}
rear++ ;
arr(rear] item ;
}
/Idisplays elements ofadeque
II counts the total number ofelements indeque
int dQue :: count( )
{
void dque :: display( )
{
int n=a.count{ ) :
cout "\nTotal number ofelements indeque:" n;
a.display( ) :
i =a.deIQatbeg( ) :
cout "\nltem extracted: " I ;
int i =a.delqatbeg( ) :
cout "\nltem extracted: " i ;
i =a.delqatbeg( ) :
cout lnltemextracted: " i ;
i =a.delqatbeg( ) :
cout "\nltem extracted: " i ;
Chapter 7: Queues
Data Structures Through C++
cout endl "front->"
for ( intj =0; i <MAX ; i ~ + )
cout " "arr[i) ;
cout <-rear" ;
intc=O;
for ( inti =0; j <MAX ; i++ )
{
if ( arr[i] !=0)
c++ ;
}
return c;
372 I I r - - - - - - ; : - - - : : - - - ~ - -
}
}
void main()
{
dque a;
cout "\/'l8ernents inadeque after deletion: ;
a.display( ) :
a.addqatend ( 16 ) ;
a.addqatend ( 7) :
a.addqatend ( 17) ;
a.addqatbeg ( 10 ) ;
a.addqatend ( 8) ;
a.addqatbeg (-9) ;
a.addqatend ( 13 ) ;
a.addqalbeg ( 28 ) ;
a.addqalend ( 14) ;
a.addqatbeg ( 5) ;
a.addQatend ( 25) ;
a.addqatbeg ( 6) ;
a.addQatenct ( 21 ) ;
a.addQatbeg ( 11 ) ;
cout "\nElements ;n adeque: " ;
cout lnElements inadeque after addition: " ;
a.display( ) ;
i =a.delqatend( ) :
cout "\nltem extracted: " i ;
i =a.delqat oo() ;
coot "\/'lItem extracted: " i :
rout "\nElements inadeque after deletion: :
a.display( ) :
n=a.count( ) ;
cout "\nTotal number of elements indeque: "n:
}
Figure 7-10. Deque after addition of first element.
that we wish to add indeed is the first element of the deque. Hence
the values of fro t and rear are set to a and the element 17 is
placed in the deque. Figure 7-10 shows the representation of a
dcque after adding one element
Chapter 7: Queues
Next we have called addqatbeg( ) function to add an element at
the front end of the deque. In this function too, before adding the
clement we have checked two conditions. First whether or not the
dcque is full and the second whether the element to be added is
first element of the deque. In our case both the conditions would
evaluate to false, since the deque is not full as holds one element-
17. Now, the element 10 should get added at the alb position, but
that position is already occupied by element 17. To make Olb
position vacant we need to shift 17 to the right. This would be
possible if there is any vacant place available to the right of the
element 17. In other words, this would be possible if the value of
rear is less than MAX. Since, 17 is the only element added to the
deque so far, it would get shifted one place to the right and the
clement 10 would now occupy the alb place.
To shift the elernenus) to the right, first we have obtained the total
number of elements present in the deque by calling the count( )
function. Next we have obtained the position of the last element in
the deque, i.e. the element at the rear end of the deque. Then,
through a loop we have shifted the elements one place to the right.
DataStructures Through C++=
]74
Deque isfuJI
Output:
Deque isfuJI
Here we have created a class called d' .
array of integers called rr to hold the ele This class centams an
data members front and rear are used toe of a deque, The
the rear end ofthe deque. monitor the front end and
In maine ) we have called add alb ()
functions alternately to add I q eg . and addqatend( )
e ements ar the bezinni d
end of the deque respective] Ltd' ...mg an at the
d
y. e us ISCUSS how the el
a ded at the front or end of the deque. ements get
First we have called add atend( ) fimcti ,
have checked h h q unction. In this function we
w er er or not the deq 'full
full' gets displayed if the deque is A message 'Deque is
whether the element to be added ' th fi xt we have checked
IS e rrst element. The element
Elements in adeque:
front-> 6 5 28 -9 10 17 8 13 14 25<-rear
Total number of elements in deque: 10
Item extracted: 6
Itemextracted: 5
Itemextracted: 28
Itern extracted: .9
Elements inadeque after deletion'
front> 0 0 0 0 10 17 8 13 14' 25 <-rear
Elements inadeque after addition'
front) 0 0 10 17 8 13 14 25 16 7 c,
ftem extracted: 7 rear
Itemextracted: 16
Elements in adeque after deletion:
front-> 0 0 10 17 8 13 14 25 0 0<-rear
Total number ofelements In deque: 6
Now, let us discuss the functions delqatbeg( ) and delqatend( ).
The delqatbeg( ) function removes an element from the front
position. After removing an element front stores the index of next
dement in the deque. Hence we have incremented the value of
front by 1. In the function delqatend( ) on removing element at
the end, rear should store the index of the element that occupies
the position to the left of the element being deleted. Hence we have
decremented the value of rear by 1.
Imagine a situation when the value of rear has reached MAX 1
and the value of front is greater than 0, say 4 for example (after
deleting first 4 elements). This would be the stage where the deque
is not full. But. it would not be possible to add an element at the
rear end of the deque. To do so the elements would be required to
be shifted one position to the left. In addqatend( ) function this
situation is handled as follows. .
Figure 7.12. Deque containing 10elements.
stage would display the message 'Deque is full'. We have called
tlisplay() function to display all the elements in a deque.
DataStructures Through C++
Before Shifti g
After Shifting

!he element is then placed at the vacant place that comes
u:unedlately the left of the element (to which fr nt is pointi
7-11 the pictorial representation of how element
shifted to the right and then a new element gets added at the vacant
place.
Figure 711. Shifting of element(s) in a deque while adding lement
at the beginning.
intk :: front - 1 ;
for ( int i =front- 1; i <rear : i++ )
{
if(rear==MAX-1)
{
At stage the value of front and rear would be 0 and I
Then we have added several elements to the d ue
After adding the element 6 values of fr t and rear would be: .
oand 9 Figure 7-12 shows deque after adding all
10 elements. Trymg to add any more elements to the deque at this
rear
rear


...... Deletion
Deletion+-
Insertion+- +-Insertion
'-!....._ .................-p.. "
Deletion
There are two variations of a deque. These are:
Input-restricted deque
- Output-restricted deque
An Input restricted deque restricts the insertion of elements at one
end only, but the deletion of elements can be done at both the ends
of a queue. Figure 7-14.illustrates an input-restricted deque.
Figure 7-14. Representation of an input-restricted deque.
On the contrary, an output-restricted deque, restricts the deletion of
elements at one end only, and allows insertion to be done at both
the ends of a deque. Figure 7-15 illustrates an output-restricted
. deque.
k=i;
if(k==MAX'l )
antk]=O;
else
arT{ k1=ant j + 1J;
Before Shlfti g
}
rear- ;
fronl- ;

}
If the condiiion given in the code snippet evaluates to true then th
value of a temporary van' bl k i e
Ii a e IS set to froot - I. Thus, if value of
ront were 4 k would be 3. Then, through for loop the
elements are shifted one position to the left. The new element is
then added at the end of the deque. Figure 7-13 illustrates shiftin
elements to the left and placing a new element at the end of
eque.
After Shifting
Figure 7-13. Shffting of elements to adda newelement at the end.
Figur 7-15. Representation of an output-restricted deque.
#include <iostream.h>
#include <string.1?
da of the item like into char, etc.,
where dataType would ~ .ta type be f the element and order
priority would be the pnonty num r 0 added to the
would be the order in which the element has been
queue. .
Given below is a program that implements the priority queue usmg
an array.
private:
struetdata
{
char job[MAX] ;
intpmo;
intord ;
}d[MAX] ;
class pque
{
};
constintMAX =5;
structdata
{
<dataType> item;
intpriority ;
intorder;
. thi bl However it would
There is no satisfactory solutionto s pro. em. . , ueue iii. an
be m
ore efficient if we store the elements 10 a pnonty q C II .
. array can have 10 owing
ordered manner. Each element in an
structure.
Chapter 7: Queues
- - - - - - - - - : - - - - I ~
Data Structures Through C++ 380 11 --:::....__
The programs for input-restricted deque and output-restricted
deque would be similar to the previous program of deque except
for a small difference. The class dque for input-restricted deque
would not contain the function addqatbeg( ). Similarly, the class
dque for output-restricted deque would not contain the function
delatbeg( ).
Priority Queue
A priority queue is a collection of elements where the elements are
stored according to their priority levels. The order in which the
elements should get added or removed is decided by the priority of
the element. Following rules are applied to maintain a priority
queue.
(a) The element with a higher priority is processed before any
element of lower priority.
(b) If there are elements with the same priority, then the element
added first in the queue would get processed.
Priority queues are used for implementing job scheduling by the
operating system where jobs with higher priorities are to be
processed first, Another application of priority queues is simulation
systems where priority corresponds to event times.
Array Implementation Of APriority Queue
Like stacks and queues even a priority queue can be represented
using an array. However, if an array is used to store elements of a
priority queue, then insertion of elements to the queue would be
easy, but deletion of elements would be difficult This is because
while inserting elements in the priority queue they are not inserted
in an order. As a result, deleting an element with the highest
priority would require examining theentire array to search for such
an element Moreover, an element in a queue can be deleted from
the front end only.
;
d[i] =dUl;
dill =temp ;
}
if ( d[i].prno = dD].pmo )
{ if ( d[i].ord > dUl ord )
{
}
}
else
{
}
for{intj=i+1 ; j <=rear ; j++ )
{
if ( d[il.prno >dli).pmo )
{
temp =d[il;
dPl =dUl ;
dOl =temp ;
1/ removes item from priority queue
data pque :: remove( )
{
data t;
strcpy (t.job. "") ;
t.pmo =0;
tord=0;
if (front:= -1 )
{ cout c "\r)Oueue endl ;
retumt;
Chapter 7: Queues
-----------11383
Data Structures Through c++
pque{) ;
void add ( data dt) ;
data remove( ) ;
public:
}
rear++ ;
d[rear] =dt ;
if ( front == -1 )
front =0;
cout inQueue isfull" ;
return ;
data temp ;
for( inti =front ; i <= rear; iH )
{
front =rear =1 ;
for ( int i =0; i <MAX ; i++ )
{
strcpy ( dPJ.job, '\0' ) ;
dpl orno =dPJ.ord =0;
intfront. rear:
382 ]1

};
/I initialises data members
pque ::pque()
{
}
1/ adds item tothe priority queue
void pque :: add ( data dt)
{
jf ( rear == MAX - 1)
{
Data Stmctures Through C++
}
Here the class pque contains an array d to hold the elements of the
priority queue. The element in the array is a structure holding
information about .the job to be processed, priority of the job, and
the order in which the element is added. The function add( ) adds
the element to the priority queue, whereas the function remove( )
deletes an element with the highest priority from the
In main( ) through a for loop, we have added 5 elements to the
priority queue. In addq( ) function, the element dt gets added to
the queue at the rear end. Suppose the first element to be added to
the queue holds data as {TYPE, 4, I}. After adding this element
the value of front and rear would be O. Next, in this function we
have arranged the elements in ascending order of their priorities.
Suppose the second element to be added to the queue is {SWAP, 3,
2}. The priority of the second element is lower than the element at
Process jobs prioritywise
Job Priority
PRNT 1
SWAP 3
SWAP 3
TYPE 4
COPY 5
Output:
Enter Job description (max 4chars) and its priority
lower the priority number, higher the priority
Job Priority
TYPE 4
SWAP 3
COPY 5
PRNT 1
SWAP 3
.
" temp.pmv endl ;
poue q;
data dt;
intj=O;
t =d(irontJ ;
d(front] =t ;
it ( front = rear )
front =rear =-1 .
else
front++ ;
retum t;
cout :Enter Job (max 4chars) and ns priorilf .
cout Lower the pnonty number, higher the priority" .
cout "Job Priority" <<: endl ; I
for( inti =0; i <: MAX ; i++ )
{
tin dt.job dt.pmo ;
dt.ord =j++;
q.add (dt);
}
cout <<: endl ;
cout "Process lobs prioritywise" endl .
cout "Job Priority" endl ; I
for ( j =0; i c MAX . i++ )
{ I
data temp =q.remove{);
cout <<: temp.job"
}
cout endl ;
void main()
{
(1) Linear data structure
(2) Non-linear data structure
(3) Both (1) and (2)
(4) None of the above
(a) Queue is a
(\I) In a circular queue implemented using an array and holding 5
clements, if front is equal to 3 and rea i ~ .equal to 4, then the
new clement would get placed at _ position.
. 11 d when addition as well as
(c) A queue is ca e
deletion of elements can take place at both the ends.
is a queue in which insertion of an
(d) ~ : m e n t takes place at one end only but deletion occurs at both
the ends.
is a queue in which insertion of an
(e) An
d em-e-n-t-ta-k-e-s-p-:-ta-c-e-a-tboth the ends but deletion occurs at one
end only.
In1 Choose the correct alternative for the following:
(a) For a queue built using an array and containing 0 elements, the
value of froot would be and rear would be
I t rcise
IAI Fill in the blanks:
rear
Data Structures Through C++
SWAP, 3, 2 SWAP, 3, 5 TYPE,4, 1
front
386 II'---- ~ __
~ .._-_...._-- I
front rear
the Om position in the queue. Hence the second element would get
placed at Om position and the element at Om position would occupy
first position. Figure 7-16 shows the priority queue after adding
two elements.
Figure 716. Priority queue after adding two elements.
In case there are two elements with the same priority, then the
elements are arranged according to their order number in which
they were entered. Thus, the elements in the priority queue are
arranged prioritiwise and within the same priority as per the order
of entry. Figure 7-17 shows priority queue after adding fifth
element.
Figure 717. Prion'ly queue with 5 elements.
Next, in order to process the information with the highest priority
we have called remove( ) function. In this function the element at
the front is removed.
(b) The end at which a new element gets added to a queue is
called
(1) A program is to keep track of patients as they check into a
clinic, assigning them to doctors on a first-come, first-
served basis.
(2) An inventory of parts is to be processed by part number.
(3) A dictionary of words used by spelling checker is to be
created.
(4) Customers are to take numbers at a bakery and be served
in order when their numbers corne up.
QI: XYZ, 1, PQR, 1, RRR, I
Q2: ABC, 2, CBZ, 2
Q3: RTZ, 3, QQQ, 3
Q4: XXX,4
The order of processing should be: QI, Q2, Q3, Q4. Write a
program to simulate the above problem.
(l:) Write a menu-driven program to simulate processing of batch
jobs by a computer system. The scheduling of these jobs
should be handled using a priority queue. The program should
allow user to add or remove items from the queue. It should
also display current status i.e. the total number of items in the
queue.
(d) Write a program to copy one queue to another when the queue
is implemented as a linked list.
(e) Specify which of the following applications would be suitable
for a First-In-First-Out queue.
Data Structures Through C++
3881[ ~ __
(I) Last-In-First-Out data structure
(2) First-In-Last-Out data structure
(3) First-In-First-out data structure
(4) Last-In-Last-Out data structure
lCJ Write programs for the following:
(1) front
(2) rear
(3) top
(4) bottom
(c) The end from which an element gets removed from the queue
is called
(I) front
(2) rear
(3) top
(4) bottom
(d) Queue is also called
(a) Write a program to represent a deque using linked list. Also
write functions to add and delete elements from the deque,
(b) Suppose there are several jobs to be performed with each job
having a priority value of I, 2, 3, 4, etc. Write a program that
receives the job descriptions and the priorities. Create as many
queues as the number of priorities and queue up the jobs into
appropriate queues . For example, suppose the priorities are I,
2,3, and 4 and the data to be entered is as follows:
ABC, 2, XYZ, I, PQR, I, RTZ, 3, CBZ, 2, QQQ, 3, XXX, 4,
RR.R, 1
Then arrange these jobs as shown below;

You might also like