DS Note by Kaustav Sir

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

DATASTRUCTUREUSING C

INTRODUCTION a
mathematical model o pa
y De organized in ditlerent forms, the logical
or

elements whose
organizato
gnaton ot data is called data structure. It is a collection of dataelements.
retrieve data
dracteti/ca by accessing operations used to store and
Data structure = organized d a t a + operations.

They are classified as

1. Linear data structures


Data items are arranged and accessed in a linear sequence ie. one after the other. T hey inude

a) Arrays
Lst ol inite number of similar data elements in continuous memory locationg.Teerenpeaoy
consecutive numbers. Size of an
array= (upper bound
-
lower bound) *1
b) Linked list which
t1s a collection of nodes. A node has one information field and other pontr tields,
contain address of other nodes.
c) Stacks
at one end
Stack is a last in first out (LIFO) system, in which insertion aúd deleioD,take place
ie. top end
d) Queue
at one end (ie. tront)
Queue is a first in tirst out (FIFO) system,
in which deletion 1ake place
and imsertiOn at the other end (ie. rear).

2. Non linear data structures


include
Data items are not arranged and accessed in a
linçaf vanner. They
) Trees It is a hierarchical notation of data eleneNS With the root at top and it grows downwards.

b) Graphs not
In this the data structures contaun a elationship between pair of elements which are

necessarily hierarchical.

Datastructure operations on the data structures are


A large number of perationsa t can b pertormed
the data structure)
1. Inserting (insertingan djeuvent into the data structure)
Deleting (deleting au elehgnt ttom
all the elements in the data structure)
Iraversing/ Dispkai1ng (VISIting printing
or

the data structure not)


given element exists in
or
Searehing (checkiug whether a

element in the data structure)


Modity ing (updasng an

6. Sorting aTaiging the elements of the data structure in a particular order)


the elements ot two or more similar data structures)
Merginguouing

ARRAYs
Array is a finite ordered collection of homogeneous or similar elements in contiguous memory

locations
Concepts
Size (ie. length or dimension)
Number ot elements Ie. (Upperbound - Lowerbound) + 1.

Type
The dataty pe of the elements
Base
The base address of the first element

Inder (ie. subscript)


The subscript number by which all elements are reterenced.
OneDimensionalarray (D)
It is d collectiom of sinnilar data elements which lie in contintuous memory locatios. It element of
the array (Say a) is at b (base address) then
*
b+i
Addressali =
w.

Where w Is the size of cach element.


If one subscript is required to reterence all the elements in the array, then it is one dimensional array
or simple array.

Operations on ID arraY
Traversal

element.

void display_array(int al ]. int size)

int
Dev(TRIDEM
Traversing reters to visiting or displaying each and every element of the arra hil the last

for i = 0; i< size; i ++)


printi od", ali|);

Insertion

vOId

int
byKaustitvG:
Inserting an clement 1s done by giving the location and then sreifting all elements after that
location, one position to the right. But before doing itbe spåe availability has to be checked.

insertion_array(int al }. int size, int n, int

for i size - 1 ; i > = pos; i - )

alialiI];
ali

Deletion
Deleting an elenent is done by giving a location and then shitting all elements from the
location onwards, andposition to the left.

void
deleon\array(int al J. int size, int
pos)

tor ( p o s - I;I Size - | ; i++)


ali= ai+ I:

Search
Searchmg reters to giv ing an element and checking it it exists in the array.

Od search
_aray(int al |. int size, nt n)

printi"Tnter the number to be searched ).


scant od".&n).
fori 0:i< size: i t+ +)

if( alil= = n)

printf(" Found");

ifi SIZc)
printf(" Not found");

Modify/Update exists in the array, theq opdaipethe


refers to giving an element and checking if it
Modifying
number to the new value.

ZOÎBI
void search_array(int al[ ], int size)

int n, m, i
printf("Enter the number to be modified and the updated value");
scanf%d%d",&n,&m);

for (i =
0; i< size; i + +)
if( a[i] == n)

alil =m
ifi= = size)
na7
printf("Not found");

Ag
DANZsnsy,
pauvdauz
STACK
tis a inear dala structure, which works on the principle of 1.IFO (Last In First Out) ad its clement

insertion nd deletion takes place nt one end, known as the top end
Stack can be represented either through arrays or through link lists

PreparedtyAaustUvDea v(IRIBEV
Array Implementationof
I s casy and sunplestack
to implement, but the size of the array must be declared in advance. Thus
an aray of lised sire is needed alomg winh a variable top (initially set at - 1), which stores the index
of the toN element.

# define MAX 5

inta MAX|:
int top = - :

Stack Operations
Insertion (Push)

austuvaDev(1RI
Insertion is done by incrementing the top and entering the new valud, but ih hust also check
the stack full condition.

void push( 0

n n,

printf"Enter the element");


scanf%d",&n);
i f t o p = = MAX - 1))

printf"Overtlow"):
else

top = top t l ;

a top]= n;

Deletion (Pop)
Deletion is dond bydecrementing the value of top, but it must check for the stack empty
a r e av J
condition.

void pop )

if(top=
Underflow");

Xop = top- 1;

Traversal / Display
Displays all elements starting from the top element till the last element.

voiddisplay_stack()

for i = top;i>=0;i-)

printf("%d un",ali]);
Applications of Stack
IS a l r O structure and which mformation saved later retricvcu
HC
the reverse order
is used for applicatioms in is

The basic applications of stack are


1. Nested funetion calls
The address and the inlormation o f ealling lunction is stored in stack., at point ot jumping and

later retrieved, to returm back from the called functin


2. Recursion
The inforimation of previous values is stored when a recursion function calls itsell with a

different value, later that information is retrieved when the function returns back.

3. Evaluation and conversion of expressions


Expression refers to a combination o f operands and operators. They are represpateu
arious
torms or notations, such as
a) Infix (General notation) b
Operatsf Opera2 Ex.
+
a
Position of operator is inbetween the operands i.e OperandI
b) Prefix (Polish notation)
+ab
Position of operator is before the operands i.e Operator Operand pETdord2 Ex.
c) Postfix (Reverse Polish notation)
Ex. b +

Position of operator is after the operands i.e Operandl Qperandh2 Opertator a

Conversion of Expressions
Conversion of Infix to Postfix (manual)
Stepl. Fully parenthesize the expression depending on the precedence of the operators
i.e )
Step2. Move all operators to replace their correspondihg rigit parenthesis
Step3. Remove all remaining parenthesis
(a+(b c-d) ) * (e-f/c)
Ex.

>(at((b )(°
=>(a ((bc^d-+(e(fc^
=>abc^d - +efc/.

Conversion of Infix to Prefix(manraty


Step1. Fully parenthesizathe enpression depending on the precedence of the operators
their corresponding left parenthesis i.e (
Step2. Move all operàtors to teplàce
Step3. Remove all remnaining parénthesis
Ex. (a+ (b grNNc-f/c)

b c d ) )-e/fc)))
P E ^bcd- elfc
Conversion of Infix to Postfix (using stack)

Algorithm
Stepl. Put a left bracket " ( into the stack and a right bracket " ) " to the end o f t h e

expression
else goto Step13
Step2. If stack is not empty gototheStep3
lelt hand side
Scan next symbol from
Step3.
Step4 If symbol is an operand then display on the output
it
Steps. I1 symbol is a " t h e n push into the stack
Siepó. Ifsymbol is an operator then goto Step7 else goto Stepl|
Step7. If top of the stack is already an operator then goto Step8 else goto Step10
Step8. I f the top of the slack 's operator precedence = scanned sy mbol's precedence then
gotoStep9 else goto Stepi0
Step9 Pop the operator from tlhe top of the stack and display on the output and then goto
Step7
Stepl0.Push the scanned symbol into the stack
S t e p l 1 . l ts y m b o l i s a * " then pop and display all elements from the stack till the first "(*

IS found and then discard the "

(*

AaustuvaDegfTRI1RIDENT
Step12.Goto Step2

ENT)
Step13.End
Ex. (a+ (b ^c
- d)) *(e -f/ c)
a t (b ^ c - d ) ) * ( e - f / c ) )

Symbol Stack Output

(
(( a

((+ ab
((+
((+
( P7
((+ d-
d-+
a u s t u vD a
abc d-+
abc^d-+
abc^d-+e
abcd-+e
C abc d-tef
abe^d-tef
abed-+efe
abed-+efc/-
abed-+efc/*

Conversion of Infix fo P'ref sing stack)

Algorithm
Stepl. Put a rightbrgkéi " ) " into the stackl and a left bracket " ( " to the beginning o f t h e

expressian
Step2. IfsHEknot empty goto Step3 else goto Step13
from the right hand side
Step n hekt symbol
is an
Step4syhboJ operand push it into the stack2
then
StepSaymbol is a "*)* then push it into the stack1
Stepó. symbol is an operator then goto Step7 e to Steppl
Step7. If top of the stack l is aiready an operator then goto Step8 else goto Step10
Step8. It the top ot the stack! 's operator precedence > scanned symbol's precedence then
gotoStepy else goto Stepl0
Step9. Pop the operator trom the top of the stackI and push it into stack2 and then goto
Step7
Step10.Push the scanned symbol into the stack1
Stepl1.If symbol is a " " then pop all elements from the stackl and push them into stack2
till the first ")* is tound and then discard the ")
*

Step12.Goto Step2
irom the stack2 and End
Step13.Pop all the elements
E (a (be-d))*(e -t/e)
((a + (b ^ c-d)) * (e - f/c)

Symbol Stackl Stack2

KERIDENI)
cf/e
cflc
cflc
cf/e
cfle
cf/e-d
cfle-d
cfle-4
*))-*

cfa-dc"
e-dcb^-
dde-dcb-a
A
iuSTWvu
u
DUcf'e-dcbat
E s t u vD a

efle-dcbat*
*+a-bcd-e/fe
Pop all elements from stack

Evaluation of expressions
Evaluation of Postfix expression

Algorithm
Step1. Put a * ) * to the end of thaExpréssion

symbol fom he left hand


side
Step2. Scan the next

else goto Step4


Step3. If symbol is " NMegoto Step7into the
Step4. lf symbol is ad operqjd then push stack
Steps. If symbol isn dperator then pop the l" and 2 element from the stack, evaluate 2h
the result into the stack
item and then push
poppedith pefätorl" popped
Step6. Goto Sfep?
iep 7. EndA

+,5,6, 3, , *
1, 2,3,, 4, ,+, 5, 6, 3, l, *)

Symbol Stack

1,2
1,2,3
(23 8)) 1,8
1, 8,4
(8-44) 1,4
(1+4=5)
5,5
5,5,6
5, 5, 6, 3
(6/3 2) 5.5.2
(5-2 3) 5.3
(5 *3= 15) I5

Evaluation of Prefix expression

Algorithm
Put a "(" to the beginning of the
expression
Stepl. from the right hand side
Step2. Scan the next symbol
else goto Step4
is a "(" then goto Step7
Step3. If symbol into the stack
is an operand then push evaluate DPped
Step4. If symbol element from the stack,

AZO
and
If symbol is an operator then pop
the T 2
Steps.
item result into the stack
item and then push the
operator 2 popped
Step6. Goto Step2
Step7. End

. , 2 , 3 , 4, 5,/, 6, 3
Ex (".*, 1, , ,2, 3, 4, , 5, 1, 6, 3
Stack
)
Symbol

6
(6/3= 2)
B,
2
2,5
6
0A)
(-2=3)
3,4
3

DnIsnpAg
3,4, 3,
(23 8) 3,4,
(8-44)

(1+4 5)
(5*3-5

QUEUE pait
Out) and its element
It is works
linearrdata stucture, whichknown
a
on the principle of FIFO (First In First
the end, while its element deletion takes place at other
at end, as rear
insertiontakes place one

endnodus tho front end. link lists.


Qucuecan be represented either through arrays or through
Y
Array Implementation of queue
It is easy and simple to implement, but the size of the array must be declared in advance. Thus
an array of fixed size is needed along with two variables front and r e a r (both initially set a t - 1).

which stores the index of the first and the last element.
# define MAX 5
inta MAXJ;
intfront=:
nt rear=
Queue Operations
Insertivn
ne nsertion Is done by
queue lul
condition, and incrementing the rear and
empty conditiom (wlhere entering the new value. but it must also check
void insert_queue() both front and rear are
intn ncremenieo
print("Enter the element"):
scant("%d",&n),
ilrear =

MAX
=

1)

Dev(TRIDENT
-

else printf"Overtlow"):
if ( rear == 1) -

rear =

rear+ |
front= front + 1:
arear= n
else

Tear rear + 1;
a rear) = n:

Deletion
Deletion is done by

epavedby'Kaustu.
condition and whether a incrementing the value of\front} but it must check for the stack empty
single element is present (where bofh front and rear are initialized to I
). -

void delete_
queue( )
iffront==- 1)
printf("Underflow"):
else if ( front== rear )

front-:
rear 1:

else

Tront -

Play
Displays all elements starting from the front element till the rear element.
void display_queue(,
int i

if(rear ==- 1)
printf" Empty");
else

for( i= iront; i <


reari t +)
printf(%d ".ali);
To
locatiOIs
arc empty.
tront time
evcn il the lelt.
which is
elements.

any to their
Limitations ofqucue then we
cannot
insert

be shilted one place


at
r e a r is
-)
(MAX
deletion all
elements
must

alter each
avond ihis,

consumin
it Is
introduced.
Physically
Circular Qucue circular queue
was

the concept
of followed by index|0
the limitation of queues
that
index|MAX- I| is
To
but logically it implies
overcome

RIDEN
the queue
ie. array,
Same as

Circular Qucue Operafions

# define MAX 5

inta [ MAX]:
intfront-i
intrear-1:
it must also check
and entering the hew value.
But
Insertion incrementing the
rear
incremented).
Insertion is done by both front andearype
full condition, and empty
condition (where

Dev
Dev
Kaust
AaustuvUva
the queue

void insert_circularqueue()

int n;
printt"Enter the element");

scanf("%d".&n);
MAX)
= =
front
if( ( (rear + 1)%
printf("Overflow ");
else i f ( rear = = - )

rear rear + I:

front= front + 1

else
repafe4,
alrear]n:

rear
afed
a rearlp
b
b y
y

6 MAX;

Delehon but it must check for the stack empty


value of front,
Deletion is done by incrementing the 1 ).
and rear are initialized to
-

front
condition and whether a single element is present (where both

void delete_circularqueue()

if(front=E- 1)
print("Undertlow");
else if ( front= rear )

Tront

rear
cIse

front (front +
1)% MAX:

Traversal /Display
Displays all elements starting from the front element till thhe rear element.

void display_circularqueue()
nt

Dangs7 037 INIOIUL/


if( rear == - 1)

printf("Empty");
else if(front < = rear)

for( i= front; i <= rear; i + +)


print("d "ali}}:
else

for i=front; i < MAX;i+ +)


printf(%d, a[i);
for( i = 0; i<=rear; i ++)
printf(od", a[i]);

Comparison between stack and queuÃ


Stack Queue
I. It is linear data structure which works on
1. It is linear data structure whielhworks
on the principle of LIO principle of FIFO
2. In this insertion and deletion takes place
2. In this insertion (iep push)and deletion
at two separate ends (ie. rear and front).
(ie. pop) takes place at sami end (ie. top).
3. A single pointer is rêquired ie tôp, thus it. 3. Two pointers are required ie. front and rear,

is comparatively tastep so comparatively slower.


4. Used by printers for printing various jobs, in
4. Used in recuçsion, nésted function calls,
conversionQkatithmetic expressions and BFS traversal and in some CPU scheduling.

evaluation'fexpressions.

You might also like