cs301 notes
TRANSCRIPT
-
8/11/2019 CS301 Notes
1/91
http://vustudents.ning.com
http://vustudents.ning.com
INTRODUCTION TO C
C has emerged as the most widely used programming language
for softwaredevelopment. Its features allow the development of well-structuredprograms. Mostcomputers directly support its data types and control structures,
resulting in theconstruction of efficient programs. It is independent of any
particular machinearchitecture or operating system, which makes it easy to write portable
programs. It isthis contribution of rich control structure and data types, portability and
conciseness thathas contributed to the popularity of C.
History of C
C programming language is basically developed for !I"#perating $ystem.!I" was developed in %&'& at bell telephone laboratories. It was
entirely written on()( * assembly language. +fter !I" has been implemented
en hompsonimplemented a compiler for a new language called used for
transporting !I" ontoother machines. was heavily influenced by C( 0asic
Cambridge (rogramminganguage1 written for writing system software. was latter modified by
)ennis 2itchiewho was also working at bell abs. 3e named the successor C. ni4
was later rewrittenin C by )ennis 2itchie, hompson and others by %&*5.
C Program Structure
+ basicfactabout computer programming is that all programs can be w
using a combination of only three control structures: $e6uential,
$elective and repetitive.he se6uential structure consists of a se6uence of program statements
that are e4ecutedone after another in order, the selective structure consists of a test
for a conditionfollowed by alternative paths that the program can follow, and the
repetitive structureconsists of program statements that are repeatedly e4ecuted while somecondition holds.
he se6uential structure can be pictorially represented as follows
Entry
Statement 1
Statement 2
Statement 3Exit+ll C programs are made up of one or more functions, each performinga particular task.7very program has a special function named main. It is special becausethe e4ecution ofany program starts at the beginning of its main function.%
+ typical C program has following sections
%. (reprocessor )irectives
8. 9lobal ariable )eclarations5. ;unctions
In a C program, preprocessor directive, if present, should come first
followed by globalvariable definition if any.
aria!"e Dec"aration in C
%. he variable can be 5% characters long.
8. he variable can be any of a--& and the underscor e.5. $hould not be a keyword.
?. ;irst character must be an alphabet
@. he variable is case sensitive
Data Ty#es
7very programming language has its own data type. he basic data
types in C are
Int - an integer;loat A a single precision floating point number
Char - a character in C character set
)ouble A a double precision floating point number
aria!"es
ariables are data obBects that are manipulated in a program.
Information can bestored in a variable and recalled later. ariables must be declared beforethey can be usedin a program.
Constants
+ constant is an entity whose value does not change during
program e4ecution.Constants are of five different types
%. Integer Constants8. ;loating point Constants5. Character Constants?. $tring Constants 8
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
2/91
http://vustudents.ning.com
http://vustudents.ning.com
C O#erators
he operators in C include
%. +rithmetic
8. +ssignment
5. 2elational?. Increment and )ecrement
@. it
'. ogical or oolean
*. Conditional e4pression
INPUT $ OUTPUT
he important aspects of C programming language are its ability
to handle input andoutput 0I/#1. + program using input / output functions must include the
standard headerfile 0stdio.h1 in it using the directive.
Printf functions %CONIO&H' STDIO&H(
printf A sends formatted output to stdout
fprintf A sends formatted output to a streamcprintf A sends formatted output to the te4t window on the screen
Scanf )unction
$canf - reads data from stdin;scanf A reads data from stream
he 97C3+2 and (C3+2 ;unction
*etc+ar' #utc+ar %STDIO&+(
- getchar is a macro that gets a character from stdin
- putchar is a macro outputs a char acter on stdout
T+e *ETCH an, *ETCHE )unction
- getch gets a character from console but does not echo to the screen- getche gets a character from console and echoes to the screengets' #utsgets01 - gets a string from stdinputs01 A outputs a string to stdout 5
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
3/91
http://vustudents.ning.com
http://vustudents.ning.com
CONDITION-. ST-TE/ENTS
If %con,ition( Statement
hen an if statement is encountered in a program, condition is
evaluated, if its value istrue, then the following statements are e4ecuted.
he if statement allows conditional e4ecution of a group of statements.
If0e"se Statement
$D!+"
If condition
$tatement %E
7lse$tatement 8E
If the condition is true then statement % is e4ecuted else statement
8 is e4ecuted 0if ite4ists1. 7lse part is optional.
.OOPS IN C
HI.E .OOP
hile loop provides the mechanism for looping as long as a specified
condition is met.he while loop should be used in applications that do not re6uire the
modification of anyvariables at each iteration.
$D!+"
+i"e %con,ition(Statements
he statement may be a single statement or a block of statements that is
to be repeated.he condition may be any e4pression, with true being any non-
-
8/11/2019 CS301 Notes
4/91
http://vustudents.ning.com
http://vustudents.ning.com
$D!+"
)or %ex#1ex#2ex#3(
statements44444&
5
9enerally e4p% is an initialiE
int aK8@LEclrscr01E
printf0:n 7nter the total number to be entered:N1Escanf0OPdN,Qn1E
printf0On 7nter the valuesN1E
for0iJ>EiGnEiRR1
if0aK iLP8JJ>1
sevenJsevenRaK iLEelsesoddJsoddRaKILESprintf0On he $um of 7ven number is PdN,seven1Eprintf0On he $um of #dd number is PdN,sodd1Egetch01ES @
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
5/91
http://vustudents.ning.com
http://vustudents.ning.com
2& rite a C #rogram to count t+e num!er of #ositi6e' negati
an, 7eronum!er in t+e gi6en "ist of num!ers&
F include Gstdio.hH
F include Gconio.hH
main01
int n, i, nposJ>, nnegJ>, nE
int aK8@LE
clrscr01Eprintf0:n 7nter the total number to be entered:N1E
scanf0OPdN,Qn1Eprintf0On 7nter the valuesN1E
for0iJ>EiGnEiRR1
if0aK iLH>1
nposJnposR%E
if0aKIL G>1
nnegJnnegR%Eelse
n
-
8/11/2019 CS301 Notes
6/91
http://vustudents.ning.com
http://vustudents.ning.com
8& rite a C #rogram to c+ec9 :+et+er t+e num!er is #rime or not&
FincludeGstdio.hH
FincludeGconio.hH
main01
int n, iE
clrscr01E
printf0:n 7nter the total number to be entered:N1Escanf0OPdN,Qn1E
for0iJ8EiGJn/8EiRR1
if0nPiJ J>1printf0On the given number is not primeN1E
breakE
S
if0nPi1
printf0On the given number is primeN1Egetch01E
S
;& rite a C #rogram to fin, :+et+er t+e gi6en num!er is
#a"in,rome or not&
FincludeGstdio.hH
FincludeGconio.hH
main01
int n, iE
int p,s,eE
clrscr01E
printf0:n 7nter the number :N1Escanf0OPdN,Qn1E
eJ>EpJnEwhile0pTJ>1sJpP%>EeJ0eU%>1RsEpJp/%>ES *
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
7/91
http://vustudents.ning.com
http://vustudents.ning.com
if0eJ J n1
printf0On the given number is palindromeN1Eelse
printf0On the given number is not a palindromeN1Egetch01E
S
E
clrscr01E
printf0On 7nter the noV1Escanf0OPdN,Qn1E
while0nTJ>1
6Jn/%>E
rJn-6U%>E
sJsRrE
nJ6ES
printf0On the sum of digits :PdN,s1Egetch01E
S
=& rite a #rogram to fin, :+et+er t+e gi6en num!er is #erfect or
not&
FincludeGstdio.hH
FincludeGconio.hH
main01int a J >Eint mE
printf0O7nter a number to check whether it is a perfect number or notnN1Eprintf0O 7nter a number nN1Escanf0OPldN,Qn1Efor 0mJ>EmGnEmRR1 W
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
8/91
http://vustudents.ning.com
http://vustudents.ning.com
if 0n P m J J > 1a J a R mE
Sif 0a J J n1printf0Othe given number is perfect number nN1E
elseprintf0Othe given number is not a perfect number nN1E
getch01E
>& rite a #rogram to fin, :+et+er t+e gi6en num!er is -rmstrong or
not&
FincludeGstdio.hHFincludeGconio.hH
main01
int s J >E
int cJ >E
int m,n,bEprintf0O7nter a number to check whether it is a perfect number or not
nN1Eprintf0O 7nter a number nN1E
scanf0OPldN,Qb1E
n J bE
while 0bH>1
c J b P %>E
s J s R 0cUcUc1Eb J b / %>E
Sif 0s J J n1
printf0Othe given number is armstrong number nN1E
elseprintf0Othe given number is not a armstrong number nN1E
getch01E
S
?& rite a C #rogram to fin, t+e gi6en num!er using "inear searc+
met+o,&FincludeGstdio.hHFincludeGconio.hHmain01int n,aK5>L,sea,flagEclrscr01E &
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
9/91
http://vustudents.ning.com
http://vustudents.ning.com
printf0On 7nter the number of terms :N1E
scanf0OPdN,Qn1Eprintf0On 7nter the values:N1E
for0iJ>EiGnEiRR1scanf0OPdN,aKiL1E
printf0On 7nter the number to be searched :N1E
scanf0OPdN,Qsea1Efor0iJ>EiGnEiRR1
if0aKiL J J sea1
flagJ%E
breakES
else
flagJ>E
Sif0flagJ J %1
printf0On he given number Pd is present in the position number
PdN,sea,i1E
else
printf0On he given number is not presentN1Egetch01E S
1@& rite a C #rogram to fin, t+e gi6en num!er using !inary
searc+ met+o,&
FincludeGstdio.hHFincludeGconio.hH
main01
int n,aK5>L,sea,flag,4,y,tE
int low,high,midE
clrscr01E
printf0On 7nter the number of terms :N1E
scanf0OPdN,Qn1E
printf0On 7nter the values:N1Efor0iJ>EiGnEiRR1scanf0OPdN,aKiL1Efor04J>E4Gn-%E4RR1for0yJ4R%EyGnEyRR1if0aK4LHaKyL1 %>
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
10/91
http://vustudents.ning.com
http://vustudents.ning.com
tJaK4LE
aK4LJaK yLEaK yLJtE
SSprintf0On he sorted numbers are :N1E
for04J>E4GnE4RR1printf0OPdnN,aK4L 1E
printf0On 7nter the number to be searched :N1E
scanf0OPdN,Qsea1E
lowJ>E
highJnEwhile0lowGJhigh1
midJ0lowRhigh1/8E
if0tGaKmidL 1highJmid-%E
if0tHaKmidL 1
lowJmidR%E
if0tJ J aKmidL1
printf0On the number Pd is present in the position PdN,t,mid
flagJ>E
breakE
Sif0mid J J% X X midJ J n1
breakES
if0flag1
printf0On he given number is not presentN1Egetch01E
S
11& rite a #rogram to #rint fi!onacci series using functions
Finclude G$)I#.3HFinclude GC#!I#.3Hvoid main01int nEvoid fibo0int1E %%
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
11/91
http://vustudents.ning.com
http://vustudents.ning.com
clrscr01E
printf0Ott (2#92+M # (2I! 37 ;I#!+CCI $72I7$ nN1Eprintf0On 7nter the number of terms to be in the series n O1E
scanf0OPdN,Qn1Efibo0n1E
getch01E
S
void fibo0int num1
int IJ%,ct,ft,stE
ft J >E
st J %Eprintf0Ot Pd t PdN,ft,st1E
while0IGJnum-81
ct J ft R stEft J stE
st J ctE
printf0OtPdN,ct1E
IRRE
SS
12& Program to #erform t+e mat rix a,,itions
Finclude Gstdio.hH
Finclude Gconio.hHvoid main01
int aK%>LK%>L,bK%>LK%>L,cK%>LK%>L,row,col,r,co,I,B,kE
clrscr01Eprintf0Ott Matri4 +dditionnN1E
printf0O7nter 2ow order of Matri4 + : O1E
scanf0OPdN,Qrow1Eprintf0O7nter Column order of Matri4 + : O1E
scanf0OPdN,Qcol1Eprintf0O7nter 2ow order of Matri4 : O1E
scanf0OPdN,Qr1Eprintf0O7nter Column order of Matri4 : O1Escanf0OPdN,Qco1Eif 00rowTJr1 XX 0col TJ co1 1printf0OMatri4 Multiplication is impossiblenN1Egetch01ES %8
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
12/91
http://vustudents.ning.com
http://vustudents.ning.com
else
printf0O7nter ;irst Matri4 7lements : O1E
for 0IJ>EIGrowEIRR1for 0BJ>EBGcolEBRR1scanf0OPdN,QaKILKBL 1E
printf0O7nter $econd Matri4 7lements : O1E
for 0IJ>EIGrEIRR1
for 0BJ>EBGcoEBRR1
scanf0OPdN,QbKILKBL1E
for 0IJ>EIGrowEIRR1
for 0BJ>EBGcolEBRR1
cKILKBL J aKILKBL R bKILKBLEprintf0Ohe resultant matri4 is nN1E
for 0IJ>EIGrowEIRR1
for 0BJ>EBGcolEBRR1
printf0OPtPdN,cK ILKBL1E
Spritnf0OnN1E
SS
13 & Program to #rint t+e factoria" num!er
Finclude Gstdio.hH
Finclude Gconio.hHvoid main01
int nE
clrscr01Eprintf0Oprogram to print the factorialnN1E
printf0Onn 7nter the number : O1E
scanf0OPdN,Qn1E
factorial0n1E
getch01E
S
void factorial0double 41double fact J %Efor0IJ%EIGJnEIRR1fact J fact U IEprintf0Ohe factorial of a given number is PdnN,fact1ES %5
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
13/91
http://vustudents.ning.com
http://vustudents.ning.com
18& Program to im#"ement t+e To:er of Hanoi
Finclude Gstdio.hH
Finclude Gconio.hH
void main01
void transfer0int,char,char,char 1E
int nE
clrscr01Eprintf0Ott #72$ #; 3+!#I nN1E
printf0O3ow many disks Y O1Escanf0OPdN,Qn1E
transfer0n, % , r , c 1E
getch01E
S
void transfer0int n, char from, char to, char temp1
if0nH>1
transfer0n-%,from,temp,to1E
printf0OMove disk Pd from Pc to Pc nN,n,from,to1E
transfer0n-%,temp,to,from1E
S
returnE
S
1;& Program to count t+e num!er of 6o:e"s' consonants',igits' :+ite s#acec+aracters an,
in a "ine of text using #ointers
Ainclude Gstdio.hH
main01
char lineKW>LE
int vowels J >E
int cons J >Eint digits J >Eint ws J >Eint other J >Evoid scanZline0char lineKL, int Upv, int Upc, int pd, int Upw, int Upo1Eprintf0O7nter a line of te4t nN1Escanf0OPK[nL,line1EscanZline0line, Qvowels, Qcons, Qdigits, Qws, Qother1E%?
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
14/91
http://vustudents.ning.com
http://vustudents.ning.com
printf0OPd Pd Pd Pd PdN,vowels,cons,digits,ws,other1E
return0>1ES
void scanZline0char lineKL, int Upv, int Upc, int Upd, int Upw,int Upo1
char cEint count J >E
while00c J toupper0lineKcountL11 TJ \ > 1
if 0c J J \+ X X c J J \7 X X c J J I XX c J J \# XX c J J \ 1
RR UpvE
else if 0c H J \+ QQ c G J \= 1RR UpcE
else if 0 c H J \> QQ c G J \& 1
RR Upd Eelse if 0c J J \ \ X X c J J \ > 1
RR UpwE
else
RR UpoE
RR countE
SreturnE
S
1
-
8/11/2019 CS301 Notes
15/91
http://vustudents.ning.com
http://vustudents.ning.com
1=& Program to im#"ement to Pasca" Triang"e
Finclude Gstdio.hHvoid main01
int iJ%,B,k,m,nEclrscr01E
printf0Vttt(ascal rianglenV1E
printf0VtttJJJJJJJJJJJJJJJnV1E
printf0V7nter the no of ines:V1E
scanf0VPdV,Qn1E
for0BJ>EBGnERRB1
for0kJ5@-8UBEkH>Ek--1
printf0V V1E
for0mJ>EmGJBERRm1
if00mJJ>1XX0BJJ>11
iJ%E
else
iJ0iU0B-mR%11/mEprintf0VP?dV,i1E
S
printf0VnV1E
S
getch01E
S
1>& Program to im#"ement sine series
Finclude Gstdio.hHFinclude Gmath.hH
void main01
float d,4,sumJ>,fact0int1E
int terms,signJ%,iE
clrscr01Eprintf0Vttt $ine $eries nV1Eprintf0Vttt JJJJJJJJJJJ nV1Eprintf0Vn7nter the " value:V1Escanf0VPfV,Qd1Eprintf0Vn7nter the number of terms:V1Escanf0VPdV,Qterms1E4J5.%?/%W>UdE %'
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
16/91
http://vustudents.ning.com
http://vustudents.ning.com
for0iJ%EiGJtermsEiRJ81
sumJsumRsignUpow04,i1/fact0i1E
signJ-signES
printf0Vnhe value of sine0P?.8f1is PW.?fV,d,sum1E
getch01ES
float fact0int n1
float fJ%E
int iE
for0iJ%EiGJnERRi1fUJiE
return0f1E
S
1?& Programs on /ani#u"ations on st rings
Finclude Gstdio.hH
void main01
int ch,i,B,l,m,sign,c,l%,kE
char nameKW>L,name%KW>L,name8KW>L,namerKW>L,nameffK W>L,ansJ]y]E
clrscr01E
printf0VtttManipulations on $tringsnV1E
printf0VtttJJJJJJJJJJJJJJJJJJJJJJJJnV1E
printf0V%.ConcatenationnV1Eprintf0V8.2eversenV1E
printf0V5.;indnV1Eprintf0V?.2eplacenV1E
printf0VChoice:V1Escanf0VPdV,Qch1E
switch0ch1
case %:
printf0VttConcatenationnV1Eprintf0VttJJJJJJJJJJJJJnV1Eprintf0V7nter the first string nV1Escanf0VPsV,name1Eprintf0V7nter the second string nV1Escanf0VPsV,name%1EiJBJ>Ewhile0nameKiLTJ]>]1 %*
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
17/91
http://vustudents.ning.com
http://vustudents.ning.com
name8KiLJnameKiLEiRRE
Swhile0name%KBLTJ]>]1
name8KiLJname%KBLEiRRE
BRRE
S
name8KiLJ]>]E
printf0V2esultant $tring in name8 isPsV,name81E
breakES
case 8:
printf0Vtt2eversenV1Eprintf0VttJJJJJJJnV1E
printf0V7nter the string nV1E
scanf0VPsV,name1E
iJBJ>E
while0nameKiLTJ]>]1iRRE
while0--iHJ>1
name%KBRRLJnameKiLE
name%KBLJ]>]E
printf0Vnhe reversed $tring isPsV,name%1E
breakES
case 5:
printf0Vntt;indnV1E
printf0VttJJJJnV1Eprintf0Vn7nter first string:V1E
scanf0V PK[nLV,name1E
printf0V7nter search string:V1E
scanf0V PK[nLV,name%1E
lJstrlen0name1E
l%Jstrlen0name%1Efor0iJ>EiGlERRi1cJ>Eif0nameKiLJJname%KcL1mJiEsignJ>E %W
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
18/91
http://vustudents.ning.com
http://vustudents.ning.com
while0name%KcLTJ]>]QQsignTJ%1
if0nameKmLJJname%KcL1
mRRE
cRRE
Selse
signJ%E
S
if0signJJ>1
printf0Vhe given string is presentV1Eprintf0VnIts starting position isPdV,iR%1E
e4it0%1E
kJ-%E
SS
if0kG>1breakE
S
if0signTJ>1
printf0Vhe given string is not presentV1E
breakE
S
case ?:
iJ>EBJ>E
strcpy0nameff,V V1Eputs0V7nter the string:V1E
scanf0V PK[nLV,name1E
fflush0stdin1Eputs0V7nter find stringV1E
scanf0V PK[nLV,name%1E
fflush0stdin1E
puts0V7nter replace str ing:V1E
scanf0V PK[nLV,namer1E
fflush0stdin1ElJstrlen0name1Estrcat0namer,V V1Ewhile0iGl1BJ>Efor0kJ>EkGW>ERRk1name8KkLJ] ]E %&
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
19/91
http://vustudents.ning.com
http://vustudents.ning.com
while0nameKiLTJ] ]QQnameKiLTJ]>]1
name8KBLJnameKiLE
RRiERRBE
S
name8KBLJ]>]ERRiE
if00strcmp0name8,name%11JJ>1
strcat0nameff,V V1E
strcat0nameff,namer1E
Selse
strcat0nameff,V V1E
strcat0nameff,name81ES
S
puts0Vstring after replacementV1E
puts0nameff1E
breakES
case @:
iJ>E
printf0V7nter $tring:V1E
scanf0V PK[nLV,name1Ewhile0nameKiLTJ]>]1
iRREprintf0Vnhe length of the given string isPdV,i1E
breakE
SS
getch01E
S
8>
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
20/91
http://vustudents.ning.com
http://vustudents.ning.com
Data Structures
-n intro,uction to CB
)ennis 2itchie at + Q ell laboratory, Murray 3ill,
^ersey,developed the programming language C in %&*8. he languages
C( and mainlyinfluenced it. It was named as C to present it as the successor of
language which was)esigned earlier by en hompson in %&*> for the first !I" system
on the )7C()(-*Computer.
Ho: to run C #rogramB
;rom the Ms )os prompt start C by typing \tc .%.8. #pen a file by selecting ;ile X #pen X ;ile name from the I)7 me
press ;5 ey
5. 2un the program by selecting 2un X 2un, #r press
CtrlR;& eyo see the program s output select indow X ser screen or pres?.
+ltR;@ ey.e may compile and run the programs from the )os command
ine like tcc ;ilename G7nterH.
+fter the program is compiled, we may run it and view the output by
typing
;ilename G7nterH
Pro!"em so"6ing using com#uter :
o solve a problem using a computer, the following steps are r e6uired :
+ program is developed using a high level progr amming langu
0programdevelopment1
he developed program is entered into a commuter 0(rogram editing
he edited program is translated and is produced as an e4ecutable
machine code.he 74ecutable machine code is run in the computer to carry out the
actual task0e4ecution1.
o implement the above steps, the programmer develops a
program and thedeveloped program is entered and edited with the help of an editor.!ormally the editor isprovided along with the compiler. +fter editing the program, thecompilation commandsus used for the translation process. hen the e4ecution commandis used to run theprogram to get the desir ed output. 8%
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
21/91
http://vustudents.ning.com
http://vustudents.ning.com
Com#i"ation :
3igh-level languages allow some 7nglish Alike words and
mathematicale4pressions that facilitate the better understanding of the logic
involved in a program.3igh-level languages are machine independent. $ince a computersystem cannot followprograms written in a high language, high language programs ar e
translated into low-level language programs and then e4ecuted.
ranslation of a high-level language program to allow le
languageprogram is done by software known as Compiler. #bBect code is an
intermediate codebetween the source code and the e4ecutable code.
.in9ing :
inker performs the linking of libraries with the obBect code, to
make thegenerated obBect code into an e4ecutable machine code. hus the obBectcode becomes aninput to the linker, which produces an e4ecutable machine code.
$ometimes programs aredivided into modules and these modules are compiled separately and
then linked by thelinker and e4ecuted.
hen running a program, the following files will be created
automatically.
#^ 0#bBect file1
7"7 074ecutable file1
ak 0ackup file1
$( 0$wap file1
Data Structures Definition)ata $tructure is a speciali
-
8/11/2019 CS301 Notes
22/91
http://vustudents.ning.com
http://vustudents.ning.com
-rray+n array is a finite collection of similar elements stored in contiguous
location.he operations done on an array are: -
Insertion
)eletion
Changing a particular element
.in9e, .ist
here are three types of linked lists. hey are: -
$ingle inked ist
)oubly inked ist$ingly Circular inked ist
)oubly Circular inked ist
Sing"e .in9e, .ist
!ode structure
Data Pointer
)ie", )ie",
he data fieldcontains the data elements that have to be stored in the lis
pointerwill point the ne4t node in the list.
he operations done on a list are: -Insertion
)eletion
Insertion
Insertion in t+e +ea, no,eo insert a node in the head node, Bust change the pointer field
newnode to point to the head node. et the new node be \ Tempand the head n
Head, then the insertion isTemp data = X;Head next = head 85
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
23/91
http://vustudents.ning.com
http://vustudents.ning.com
Insertion in t+e mi,,"e no,e
o insert in the middle node we need to change two pointers
the newnode be \ Tempand the present node is Present and,the ne4t node present node is future. he pointers used are \ datafor the dataX to the pointer field, the data to be inserted is \ then the insert
Temp data = X
Present next = temp
Temp next = future
Insertion in t+e "ast no,e
o insert an element in the last position Bust change the pointer field
the presentlast node to point to the new node, then set the pointer field of the n
node toNULL.et the new node be \ Tempand the present node isPre
pointers used are \data for the data field, next to the pointer fieldthe data
inserted is \X then the insertion is
Present next =Temp
Temp next =null Temp data = X
)eletion
De"etion in t+e +ea, no,e
o delete a node in the head node, Bust point the head node as the
second node. Head,et the head node be and then the deletion is
Head next = head
De"etion in t+e mi,,"e no,e
o delete a node in the middle we need to change two pointers. et th
node to bedeleted is \Temp Prand the node previous to the node to be deletedfuture.and,the ne4t node to the present node is he pointers used
the data field, next to the pointer field , the data to be inserted th
insertion is
Present next = future
De"etion in t+e "ast no,eo delete an element in the last position Bust change the pointer ftheprevious node to the last tonull . et the last node be \Tempand the prPresent. datanode is he pointers used are \ for the data fiethe data to be inserted is \ X pointer field, then the insertion isPrevious next =NULL 8?
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
24/91
http://vustudents.ning.com
http://vustudents.ning.com
Sing"y Circu"ar .in9e, .ist
he advantage of using Circular inked ist is the last nullpointer is replaced a
pointer field of the last node points to the first node, due to this circularar rangement thetraversing become 6uite easier. he insertion and deletion in the first
and middle aresame as singly linked list e4cept the last node.
Insertion
Insertion in t+e "ast no,e
o insert a node in the last position, insert the new node after the
current last node,and then change the pointer field of the new node to point to the first
node. et thelast node be last, the new node to be inserted to be ne,the first node in the lisfirst.he pointers used are \ data for the data field, nextto the pointethto be inserted is \X then the insertion is
Last next = ne
Ne next =first
)eletion
De"etion in t+e "ast no,e
o delete a node in the last position, change the pointer field
previous node to the current last to point the first node. et the lasbe last, the previous node to the cur rent last node to be prthe firsdatain the list to be first.he pointers used are \ for the data
the data to be inserted is \X to the pointer field, then the dele
Prev next = first
Stac9
+n important subclass of lists permits the insertion and deletionelement to occur only at one end. + linear list of this type is known a
he insertion is referred to as \push. he deletion is referred to as \h
pointers used for accessing is top Q #ottom pointer.
($3 A $toring the element into the stack.ottom (ointerCheck topGJ allowed si
-
8/11/2019 CS301 Notes
25/91
http://vustudents.ning.com
http://vustudents.ning.com
8. 2ear 0sed for insertion1
Insertion Bif rearHn 6ueue overflow
else
increment the rear pointer and insert the value in the rear position.
De"etion BIf front J> then 6ueue underflow
7lse
Increment the front pointer and return the front-% value
Tree
+n important class of digraph, which involves for the description of
hierarchy. +directed tree is an acyclic digraph which has one node called rootwith in degree >,
other nodes have in degree %. 7ver y directed tr ee must have at least
one node. +n isolatednode is also called as directed tree. he node with out degree as > is
called as leaf. helength of the path from root to particular node level of the node. If the
ordering of thenode at each level is prescribed then the tree is called as ordered tree.
inary TreeIf a tree has at most of two children, then such tr ee is called as inar
tree. If theelements in the binary tree are arranged in the following order
.eft e"ement is "esser t+an t+e root
Rig+t e"ement is greater t+en t+e root
No ,u#"ication of e"ements
hen such binary tree is called as inary Searc+ Tree
O#erations #erforme, in a !inary tree areB
o Inserting a node
o )eleting a nodeo raversing the tree
Tra6ersing /et+o,s
1& (re A order method
2& In A order method3& (ost A order method8& Converse (re A order method;& Converse In A order method
-
8/11/2019 CS301 Notes
26/91
http://vustudents.ning.com
http://vustudents.ning.com
Pre or,er met+o,
his method gives the tree key value in the following manner: -
%. (rocess the root8. raverse the left sub tree
5. raverse the right $ub tree
In or,er met+o,
his method gives the tree key value in the following manner: -%. raverse the left sub tree
8. (rocess the root
5. raverse the right $ub tree
Post or,er met+o,
his method gives the tree key value in the following manner: -
%. raverse the left sub tree
8. raverse the right $ub tree5. (rocess the root
Sorting
$orting is, without doubt, the most fundamental algorithmic problem
%. $upposedly, 8@P of all C( cycles ar e spent sorting
8. $orting is fundamental to most other algorithmic problems, for e4am
binarysearch.5. %an&different approaches lead to useful sorting algorithms, and these
canbe used to solve many other problems.
hat is sortingY It is the problem of taking an arbitrary permutation of nitem
rearran'in'them into the total order,
Issues in SortingIncreasing or Decreasing Order?- he same algorithm can be used by both all wdo is change to in the comparison function as we desire.What about equal keys?A May be we need to sort on secondary keys, or leavesame order as the original permutations. 8*
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
27/91
http://vustudents.ning.com
http://vustudents.ning.com
What about non-numerical data?- +lphabeti
-
8/11/2019 CS301 Notes
28/91
http://vustudents.ning.com
http://vustudents.ning.com
and then we recursively reestablish the heap property as follows: if the
parent is greaterthan a child, swap the parent with the highest priority child. eep
swapping until no moreswaps are possible. $o in the above tree, first we would swamp ? with W.
W/
? 8
/'
hen we would swap ? with '.
W
/
' 8
/?
he final swap yields a heapT
he cost of removing an item 0reheapifiying after removing the item1 is
#0log n1. healgorithm Bust traverses one path in the tree, which is #0log n1 in length.
;or each nodeon that path it performs at most two comparisons and one swap 05operations -H constanttime1. $o overall the algorithm has a worst case time comple4ity of
#0log n1.
$pace comple4ity is #0n1 since a se6uential array representation can be
used.
uic9 sort
is a very efficient sorting algorithm invented by C.+.2. 3oarer. It has
twophases:
he partition phase and
he sort phase.
+s we will see, most of the work is done in the partition phase - it worksout where todivide the work. he sort phase simply sorts the two smaller problems
that are gener atedin the partition phase.
his makes _uick sort a good e4ample of the ,i6i,e an, conFuersstrategy for s
problems. 0Dou]ve already seen an e4ample of this approach in the binar
y searchprocedure.1 In 6uick sort, we divide the ar ray of items to be sorted into
two partitions andthen call the 6uick sort procedure recursively to sort the two partitions, i.eproblem into two smaller ones and !on$uerby solving the smaller ones. hcon6uer part of the 6uick sort routine looks like this:8&
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
29/91
http://vustudents.ning.com
http://vustudents.ning.com
6uicksort0 void Ua, int low, int
high 1
int pivotE
/U ermination conditionT U/if 0 high H low 1 Initial $tep - ;irst (artition
pivot J partition0 a, low, high
1E
6uicksort0 a, low, pivot-% 1E6uicksort0 a, pivotR%, high 1E
S
S
$ort eft (artition in the same
;or the strategy to be effective, the partitionphase must ensure that all the items part 0the lower part1 and less than all those in the other 0upper1 part.
o do this, we choose a pivotelement and ar range that all the items in the lower p
less than the pivot and all those in the upper part greater than it. In themost general case,we don]t know anything about the items to be sorted, so that any
choice of the pivotelement will do - the first element is a convenient one.
DiG9stras -"gorit+m
)Bikstra]s algorithm 0named after its discover, 7.. )iBkstra1 solves theproblem offinding the shortest path from a point in a graph 0the sour!e1 to a destination. It tur
that one can find the shortest paths from a given source to allpoints in a graph
same time, hence this problem is sometimes called thesing"e0source s+ortestproblem.
*ra#+ Tra6ersa"
$ystematic traversals of gr aph are similar to preorder and post order
traversal for trees.here are two graph traversals, depth- first and breadth-first search.
;re6uently the graphsearches start at an arbitrary verte4. he searches are efficient if they
are done in #0m1, where nis the number of vertices and mthe number of edges.9raph traversal can be used to determine the general characteristic ofthe graph, or tosolve a specific problem on a particular graph, for e4ample:2outing phone calls, or packets(lanning a car tripocate particular vertices, for e4ample a win position in a game.5>
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
30/91
http://vustudents.ning.com
http://vustudents.ning.com
De#t+0first Searc+
e start the graph traversal at arbitrary vertices, and go down a
particular branch until wereach a dead end. hen we back up and go as deep possible. In this
way we visit allvertices, and all edges.
reat+0)irst Searc+
readth-first search visit all adBacent vertices before going deeper.
hen we go deeper inone of the adBacent vertices.
S#arse /atrix B
+ matri4 consists of more number of
-
8/11/2019 CS301 Notes
31/91
http://vustudents.ning.com
http://vustudents.ning.com
@ top
&
%
5*
3ere, @ is the current of the stack. If we add any element in the stack, it
will be placed ontop of @ , and if we delete an element , it will be @, which is on top of
the stack.
O#erations on Stac9sB
+ssociated with the stack , there ar e several primitives operations. e
can definethe following necessary operations on stack.
a1 create0s1 - o create s as an empty stack.
b1 push0s,i1 - o insert the element I on top of the stack s.
c1 pop0s1 - o remove the top element of the stack and to return
the removedelement as a function value.
d1 top0s1 - o return the top element of stack0s1.
e1 empty0s1 - o check whether the stack is empty or not. It returns
true if stack isempty and returns false otherwise.
If a stack is empty and it contains no element, it is not possible to pop
the stack.herefore, before popping an element, we must ensure that the stack is
not empty.
PUSH POP OPER-TIONSB
+en :e a,, an e"ement to a stac9' :e stay t+at :e #us+ it on t+e
stac9 an, if :e ,e"ete an e"ement from a stac9' :e say t+at :e #o# it
from t+e stac9&.et us see +o: stac9 s+rin9s or gro:s :+en :e #o# or #us+ an
e"ement in t+efo""o:ing figures&
Pus+ %>( on t+e stac9 58
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
32/91
http://vustudents.ning.com
http://vustudents.ning.com
W top
@
&
%5
*
(ush 0?1 on to stack
? top
W
@
&
%
5
*
(op an element from the stack
op (opped element J ?W
@
&
%
5
*
(op an element from the stack 55
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
33/91
http://vustudents.ning.com
http://vustudents.ning.com
op (opped element J W@
&%
5
*
e may notice that the last item pushed onto a stack is always the first
that will bepopped from the stack. hat is why stack is called last in, first out or
I;# in short.
Im#"ementation of Stac9s
T+ere are t:o :ays to im#"ement stac9s' one using arrays an,
ot+er isusing "in9e, "ist&
-rrayB$ince the elements of the stack are ordered , an obvious choice would
be an arrayas a structure t contains a stack. e can fi4 one end of the array as
bottom of the stack.he other end of the array may be used as a top of the stack,
which keeps shiftingconstantly as items are popped and pushed. e must store the
inde4 of the arraycontaining the top element.
e can , therefore, declare a stack as a structure containing two fields-
an array to holdthe elements of the stack, and an integer top to indicate the position of
the current top ofthe stack within the array.
F define M+" @>
struct stack
int topE
int elements K@LE
SEstruct stack sE3ere s is defined to be a stack containing elements of typeinteger . he ma4imumnumber of elements in the stack is defined to be @>. 7lements K>Lcontain the first elementso that the value of top is >. If there are five elements in the stack, thevalue of top will befour and the top element is in elementsK?L. 5?
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
34/91
http://vustudents.ning.com
http://vustudents.ning.com
+ stack is empty when it contains no elements we can indicate this by
making top as A%.e can write our function clearstack as
clearstack0ts1struct stack UtsE
ts-Htop J -%ES
+nother operation is to check whether the stack is empty. o do
this we must checkwhether s.top J J -%.
et us now consider the ($3 operation . o push or add an element
we must performthe two steps:
i. increment top indicator ii. put the new element at the new top.
e might code the ($3 Q (#( operations as follows:
push0ts,41
$truct stack UtsE
Int 4E
if 0fullstack0ts11
printf0 O PsN, O $tack overflowN1E
e4it0%1E
S
elsets-HelementsKRR0ts-Htop1L J 4E
returnES
his routine increments the top by % and puts 4 into array
s.elements at the new topposition. In this routine we use another routine ;ull $tack which checks
whether the stackis full, before we push an element onto stack. + stack is full when ts-
Htop J J M+"-%.
;ull $tack routine as follows:
fullstack 0ts1struct stack UtsEif 0 ts-Htop J J M+"-%1return0%1Eelsereturn0>1ES 5@
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
35/91
http://vustudents.ning.com
http://vustudents.ning.com
o remove an element or pop an element from the stack, we must first
checkthe possibility of underflow as it is 6uite possible that somebody tries to
pop an elementfrom an empty stack. herefore, we can write function (#( as,
(op0ts1
struct stack UtsE
if 0empty0ts11
printf0 O P sN , O stack underflowN1E
return0>1E
else
return0ts-HelementsKts-Htop--L1ES
e can write function empty 0s1 that returns % if the stack is
empty and > if it is notempty as follows:
empty0ts1
struct stack UtsE
if 0 ts -H top J J -%1return 0%1E
else
return0>1E
S
$tack as a inked ist 0 sing (ointers1:sing this representation we are using the pool of available nodes and
wewill never have to test whether a particular stack is full. e can declaresuch as a stack asfollows.
!ode structure: 7ach node has two fields. i.e. )ata and !e4t field
)ata field !e4t field
$tack- !ode representation:+ C )$tack 7nd nodeop element 5'
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
36/91
http://vustudents.ning.com
http://vustudents.ning.com
)eclaration : 0 sing CRR1
F include Giostream.hH
F include G process.hHclass sta
struct node
int dataEnode U ne4tE
S Ustack E
public :
void push01E
void pop01E
void disp01ES
PUSH OPER-TIONB
oid sta :: push01
int nE
node tempE
temp J new nodeE 5
cout GG O (ush the element O GG endlE 0 ;irst node of
temp the stack1.
cin HH temp-HdataEtemp-Hne4tJ!E stack
if0stackJ J !1stackJtempE
else 5
temp-Hne4tJstackE stack
stackJtempE ?
S ?
temp
S
? 5stackPOP O#erationBstack 8 ? 5oid sta :: pop01 5*
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
37/91
http://vustudents.ning.com
http://vustudents.ning.com
temp
node UtempEif 0stackJ J !1
cout GG O $tack is empty O GG endlEelse stack
tempJ stackE
stackJ stack-Hne4tE tempcout GG O(opped element O GG endlE
cout GG temp-HdataE
delete tempE
S
S
TREE TR-ERS-.B
hen traversing a binary tree, we want to treat each node and its sub
trees in thesame fashion. If we let , , and 2 stand for moving left, visiting the
node, and movingright when at a node, then there are si4 possible combinations of tree
traversal: 2,2, 2, 2, 2, and 2. If we adopt the convention that we
traverse left beforeright, then only three traversals remain : 2, 2 and 2. o these
we assign thenames inorder, postorder, and preorder, respectively, because of the
position of the with respect to the and the 2.
Proce,ure for Preor,erB
%. isit the root node.8. raverse the eft sub tree in preorder.
5. raverse the 2ight sub tree in preorder.
Exam#"eB
)ig&1
he result is : R + 5W
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
38/91
http://vustudents.ning.com
http://vustudents.ning.com
-"gorit+mB
void preorder0node Unodeptr1
if 0 nodeptr TJ !1
printf0OPdnN, nodeptr-Hdata1E /U visit the root node U/preorder0nodeptr-Hleft1E /U raverse the left sub tree U/
perorder0nodeptr-Hright1E /U raverse the right sub tree U/
S
S
Proce,ure for Inor,erB
%. raverse the eft sub tree in inorder.
8. isit the root node5. raverse the 2ight sub tree in inorder.
)ig&2
he result is : + R
void inorder0 node Unodeptr1
if 0 nodeptr TJ !1
inorder0nodeptr-Hleft1E /U raverse the left sub tree U/
printf0OPdnN, nodeptr-Hdata1E /U isit the root node U/
inorder0nodeptr-Hright1E /U raverse the right sub tree U/
SSProce,ure for Postor,erB%. raverse the eft sub tree in postorder.8. raverse the 2ight sub tree in postorder.5. isit the root node. 5&
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
39/91
http://vustudents.ning.com
http://vustudents.ning.com
)ig&3
he result is : + R
void postorder0 node U nodeptr1
if 0nodeptr TJ !1
postorder0nodeptr-Hleft1E /U raverse the left sub tree U/
postorder0nodeptr-Hright1E /U raverse the right sub tree U/printf0OPdnN, nodeptr-Hdata1E /U isit the root node U/
SS
;ig.?
(27 #2)72 : +,,),C,7,+!) ;I! #2)72 : ,),+,7,;,C(#$#2)72 : ),,;,7,C,+!) + ?>
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
40/91
http://vustudents.ning.com
http://vustudents.ning.com
;ig.@.
(27#2)72 : U R + / C )
I!#2)72 : + R U C / )
(#$#2)72 : + R C ) / U
IN-RJ SE-RCH TREES
DefinitionB
+ binary search tree is a binary tree. It may be empty. If it is not empty
thenit satisfies the following properties:
%. 7very element has a key and no two elements have the same key.8. he keys in the left sub tree ar e smaller than the key in the root.5. he keys in the right sub tree are larger than the key in the root.?. he left and right sub trees are also binar y search trees.It has two operations. hey are,%. Insertion8. )eletion ?%
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
41/91
-
8/11/2019 CS301 Notes
42/91
http://vustudents.ning.com
http://vustudents.ning.com
?5
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
43/91
http://vustudents.ning.com
http://vustudents.ning.com
o delete a particular node from the inary search tree:
1& .eaf no,e
)eletion of a leaf node is 6uite easy. o delete 8W from thebelow tree the left child field of its parent is set to > and the node
disposed. o delete the%* from this tree, the right-child field of %@ is set to > , and the node
containing %* isdisposed.
o delete a leaf node 8W
o delete a leaf node %* ??
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
44/91
http://vustudents.ning.com
http://vustudents.ning.com
2& Non0"eaf no,eB
he deletion of a non-leaf element or node that has only one child is
also easy. henode containing the element to be deleted is disposed, and the single-child takes the placeof the disposed node.$o, to delete the element %@ from the above tree, we simply change thepointer from theparent node 08@1 to the single-child node0%51.?@
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
45/91
http://vustudents.ning.com
http://vustudents.ning.com
3& Root no,eB
hen the element to be deleted is in a non-leaf node that
has two children, the element is replaced by either the largest element inits left sub treeor the smallest one in its right sub tree. hen we proceed to delete this
replacing elementfrom the sub tree from which it was taken.
If we wish to delete the element with key 8@ from the above tree, thenwe replace it byeither the largest element, %* , in its left sub tree or the smallestelement , 8' , in its rightsub tree. $uppose we opt for the largest element in the left sub tree. he%* is moved into the root and the following tree is obtained.?'
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
46/91
http://vustudents.ning.com
http://vustudents.ning.com
HE-PS
Priority ueueB
he priority 6ueue is a data structure in which the intrinsic ordering of
theelements does determine the results of its basic operations. here are
two types of priority6ueues:
+n ascending priority 6ueue and a descending priority 6ueue.
+n ascending priority 6ueue is a collection of items into which items
can be insertedarbitrarily and from which only the smallest item can be removed. +descending priority6ueue is similar but allows deletion of only the largest item.
Hea#s DefinitionB
+ ma4 0min1 heap is a tree in which the key value in each node is no
smaller0larger1 than the key values in its children 0if any1. + ma4 heap is a
complete binary treethat is also a ma4 tree. + min heap is a complete binary tree that is also
a min tree.
?*
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
47/91
http://vustudents.ning.com
http://vustudents.ning.com
/ax& Hea#
/in& Hea#
UEUEDefinitionB+ 6ueue is an ordered collection of items from which items may bedeleted at oneend 0 called the front of the 6ueue1 and into which items may beinserted at the other end0 called rear of the 6ueue1. his data structur e is commonly known as;I;# or first-in-first-out. ?W
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
48/91
http://vustudents.ning.com
http://vustudents.ning.com
)ig&1
5 '
)ig&2
5 ' W
OPER-TION S ON UEUESB
It has two operations. hey areInsertion
)eletion
Insertion an element is popularly known as 7!_ and deleting an
element is known as)7_. + minimum set of useful operations on 6ueue includes the
following.i. C27+7_0_1 A which creates _ as an empty _ueue.
ii. 7!_0i1 A which adds the element I to the rear of a 6ueue and retur
new6ueue.
iii. )7_0_1- which removes the element at the front end of the 6ueu
returnsthe resulting 6ueue as well as the removed element.iv. 7M(D0_1- It checks the 6ueue whether it is empty or not and r
true ifit is empty and returns false otherwise.
v. ;2#!0_1- which returns the front element of the 6ueue withouchangingthe 6ueue.
vi. _77$I=70_1-which returns the number of entries in the 6ueue can obtain the 6ueue by the following se6uence of operations. eassume that the6ueue in initially empty. ?&
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
49/91
http://vustudents.ning.com
http://vustudents.ning.com
7!_06,W1
@ * W
7!_06,&1
@ * W &
7!_06,?1
@ * W & ?
4 J)7_061 7lement @ is deleted
* W & ?
4 J)7_061 7lement * is deletedW & ? @>
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
50/91
http://vustudents.ning.com
http://vustudents.ning.com
I/P.E/ENTIN* THE UEUE
here are two ways to implement 6ueue, one using arrays, and
another is using inked list.
i& -rray B
et us implement the 6ueue within an array so that the array holds theelements of the 6ueue. here are two variables front and rear to indicate
the positions ofthe first and last element of the 6ueue within the array.
et the si and rear J -%.
Em#ty ueueB
6K>L 6K%L 6K8L 6K5L
front J >0array position1 rear J -% 0 !1
InsertionB
here are two variables front and rear to indicate the positions of the
first andlast element of the 6ueue within the array. et the si and rear J
-%.+fter we have addedthree elements to the 6ueue rear becomes 8 and front becomes >. !ow if
we add onemore elements to the 6ueue from the rear, the value of rear changes to 5.
!ow the 6ueuebecomes full.
7!_06,51 56K>L 6K%L 6K8L 6K5Lfront J > rear J> @%
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
51/91
http://vustudents.ning.com
http://vustudents.ning.com
7!_06,@1
5 @
6K>L 6K%L 6K8L 6K5L
front J > rear J %
7!_06,*1
5 @ *
6K>L 6K%L 6K8L 6K5L
front J > rear J 8
7!_06,&1 K _ is full L
5 @ * &
6K>L 6K%L 6K8L 6K5L
front J > rear J 5De"etionB
+t this point, we delete one element. he element which is deleted is 5.
hisleaves a hole in the first position. o delete this element we must
increment front, toindicate the true first element of the 6ueue and assign the value of that
slot to 4. o checkwhether 6ueue is empty or not, we must check whether front J rear.
o add an element we must increment rear so that it points to the
location ne4t to the rearand place an element in that slot of the array. If we wish to add another
element, and weincrement rear by %, rear becomes e6ual to front, which indicates thatthe 6ueue is full."J )7_061 @ * &6K>L 6K%L 6K8L 6K5L @8
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
52/91
http://vustudents.ning.com
http://vustudents.ning.com
front J % rear J 5
4J)7_061
* &
6K>L 6K%L 6K8L 6K5L
front J 8 rear J 5
4J)7_061
&
6K>L 6K%L 6K8L 6K5L
front J 5 rear J 5
4J)7_061 K _ueue is emptyL
6K>L 6K%L 6K8L 6K5L
front J rear J -%0!1
herefore, the condition for full 6ueue is that the ne4t slot of rear is
e6ual to front and thecondition for empty 6ueue is that front J rear. efore we )7_ an
element from 6ueue wemust make sure that 6ueue is not empty and before we 7!_ an element
we must ensurethat the 6ueue is not full.
_ueue implementations in +22+D using CRRclass 6u(ublic :Int front, rear, n , 6K%>LEvoid get01 @5
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
53/91
http://vustudents.ning.com
http://vustudents.ning.com
coutGG O 7nter the _ueue siLE
void 6u :: en601
int itemE
if 0 rear HJ n1
cout GG O _ueue is full nNE
returnE
Selse
cout GG O 7nter the item to be insertedN GGendlE
cinHHitemE
rear J rearR%E6KrearL J itemE
iRRE
S
S
void 6u :: de601
int tE
if 0 front HJ rear1
cout GG O _ueue is 7mptyN GG endlE
returnE
S
else
front J fornt R%Et J 6KfrontL Ecout GG O he deleted element : O GG t GG endlESS @?
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
54/91
http://vustudents.ning.com
http://vustudents.ning.com
Im#"ementation of ueue as .in9e, "ist
+nother way of implementing 6ueues is as a linked list.et us have two pointers, front to the first element of the list and rear to
the last elementof the list.
? '
frontW
rear
.
class 6ue
struct node
int dataE
node Une4tE
S U front, UrearE
public:
void ins601E
void del601E
6ue01
front J rear J !ES
SE
void 6ue :: ins601 temp
int nE?node UtempE
temp J new nodeE front
cout GG O Insert the element O GG endlEcin HH nE
temp-data J nEtemp-Hne4t J !Eif 0 front J J !1front J rearJtempEelse ? @rear-Hne4t J tempE frontrearJ rear-Hne4tE rear@@
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
55/91
http://vustudents.ning.com
http://vustudents.ning.com
S
S
void 6ue :: del601
?node UtempE
temp J frontE temp '
if 0 front J J !1 front
cout GG O _ueue is empty O GG endlE
else
rearfront J front- Hne4tE
cout GG temp-HdataE
delete tempE
S
S
DEUEB
+ single 6ueue behaves in a ;I;# manner in the sense that each deletion
removes theoldest remaining item in the structure. + double ended 6ueue or de6ue,
in short is a linearlist in which insertions and deletions are made to or from either end of
the structure.
)eletion Insertion
Insertion )eletion
;ront 2ear
e can have two variations of a de6ue, namely, the input-restricted
de6ue and the outputArestricted de6ue. he output-restricted de6ue allows deletion from only
one end andinput-restricted de6ue allows insertions at only one end.
ueue -##"icationsB
he most useful application of 6ueues is the simulation of a real world
situation so that it is possible to understand what happens in a real world
in a particularsituation without actually observing its occurrence._ueues are also very useful in a time-sharing computer system wher emany users sharethe system simultaneously. henever a user re6uests the system to run a
particularprogram, the operating system adds the re6uest at the end of the 6ueueof Bobs waiting to
be e4ecuted. henever the C( is free, it e4ecutes the Bob, which is atthe front of the
Bob 6ueue. $imilarly there are 6ueues for sharing I/# devices. 7achdevice maintains itsown 6ueue of re6uest. @'
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
56/91
http://vustudents.ning.com
http://vustudents.ning.com
+nother useful application of 6ueues is in the solution of
problems involving searching a nonlinear collection of states. _ueue is
used for finding apath using breadth-first-search of graphs.
.INKED .IST
DefinitionB+ collection of node is called list. 7ach node or item in a linked list
mustcontain at least two fields, an information field or data field and the ne4t
address field.he first, field contains the actual element on the list which may be asimple integer, acharacter, a string or even a large record. he second field, which is a
pointer, containsthe address of the ne4t node in the list used to access the ne4t node. +
node of a linkedlist may be represented by the following figure.
)ata or !e4t
Infoist
0 74ternal pointer1
he entire linked list is accessed from an e4ternal pointer ist pointing
to the first node inthe list. e can access the first node through the e4ternal pointer, the
second nodethrough ne4t pointer of the first node, the third node through the ne4t
pointer of thesecond node till the end of the list.
he ne4t address field of the last node contains a special value, known
as the !value. his is not a valid address. his only tells us that we have
reached the end of thelist. e will draw linked lists as an ordered se6uence of nodes with
links beingrepresented by arrows.
ist? @ '
OPER-TIONS ON .INKED .IST
here are five basic types of operations associated with the list
data abstraction:
%.o determine if the list is empty. 2eturnif the list contains no elements.8. +dd new elements any in the lis5.o check if a particular element is prethe list.?.o delete a particular element from tplaced anywhere in the list.@. o print all the elements of the l@*
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
57/91
http://vustudents.ning.com
http://vustudents.ning.com
e will introduce some notations to be used in algorithms:
If p is a pointer to a node, then
node0p1 refers to the node pointed to by p
info0p1 refers to the data part of that node
ne4t0p1 refers to the address part of that node
info0ne4t0p11 refers to the data part of the ne4t node which node, which
follows node0p1in the list if ne4t0p1 is not null.
e can initiali
-
8/11/2019 CS301 Notes
58/91
http://vustudents.ning.com
http://vustudents.ning.com
list J p
e are assuming that the operation getnode0p1 obtains an empty node
and sets thecontents of a variable named p to the address of that node.
p
9etnode0p1
p4
Info041 J p
p ist
4 @ '
ne4t0p1 J list
ist
? @ 'p
list J p
Sam#"e #rograms B
Ex& No& 1 Stac9
ProgramB
FincludeGstdio.hH
FincludeGconio.hHint topJ%Eint aK8>LEvoid main01int n,4,b,c,i,tempEclrscr01Eprintf0V7nter the no of elementsnV1E @&
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
59/91
http://vustudents.ning.com
http://vustudents.ning.com
scanf0VPdV,Qn1E
do
printf0V%.($3nV1E
printf0V8.(#(nV1Eprintf0V5.)I$(+DnV1 E
printf0V?.7"InV1E
breakE printf0Venter your choicenV1E
scanf0VPdV,Qb1E
switch0b1
case %:
printf0Venter the numbernV1E
if0topHJnR%1
printf0Vnstack is overflownV1Eelse
scanf0VPdV,Q41E
aKtopLJ4E
topJtopR%E
breakEcase 8:
if 0topGJ>1
printf0Vstack is under flownV1E
else
topJtop-%EtempJaKtopL E
SbreakE
case 5:for0iJ%EiGtop-%EiRR1
printf0VPd-- HV,aK iL1E
printf0VPdV,aKtop-%L1E
breakE
case ?:
e4it0>1ESprintf0Vndo you want to continue0%/>1nV1Escanf0VPdV,Qc1ESwhile0cJJ%1Egetch01ES '>
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
60/91
http://vustudents.ning.com
http://vustudents.ning.com
Ex& No& 2 ueue
ProgramB
FincludeGstdio.hHFincludeGconio.hH
int n,4,b,c,i,rJ>,fJ>,teE
int 6K8>LE
void main01
clrscr01Eprintf0V7nter the no of elementsnV1E
scanf0VPdV,Qn1E
do
printf0V%.insertionnV1E
printf0V8.deletionnV1E
printf0V5.displaynV1E
printf0V?.e4itnV1E
printf0Venter your choicenV1Escanf0VPdV,Qb1E
switch0b1
case %:
insert01E
display01EbreakE
case 8:delet01E
display01E
breakEcase 5:
display01E
breakE
case ?:
e4it0>1ESprintf0Vndo you want to continue0%/>1nV1Escanf0VPdV,Qc1ESwhile0cJJ%1Egetch01ES '%
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
61/91
http://vustudents.ning.com
http://vustudents.ning.com
insert01
if0rHJn1
printf0Vn6ueue is overflownV1E
else
printf0Venter the numbernV1E
scanf0VPdV,Q41E
rJrR%E
6KrLJ4E
S
if0fJJ>1fJ%E
return0>1E
S
int delet01
int teE
if 0fJJ>1
printf0V6ueue is under flownV1Eelse if 0fJJr1
fJ>ErJ>E
S
else
teJ6KfLE
fJfR%ES
return0te1E
Sdisplay01
if0rJJ>1
printf0V 6ueue is emptyV1E
Selsefor0iJfEiGrEiRR1printf0VPd-- HV,6KiL 1Eprintf0VPdV,6KrL1ESreturn0>1E '8
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
62/91
http://vustudents.ning.com
http://vustudents.ning.com
S
Ex& NoB 3 Sing"y .in9e, "ist
ProgramB
FincludeGstdio.hH
FincludeGconio.hH
Fdefine null >
int a,sE
struct node
int dataE
struct node UlinkE
SE
struct node Uhead,Ufirst,Uprevious,UtempEvoid main01
firstJnullE
headJnullE
clrscr01E
do
printf0V%.creationnV1E
printf0V8.displaynV1E
printf0V5.insert firstnV1Eprintf0V?.insert lastnV1E
[email protected] middlenV1Eprintf0V'.delete firstnV1E
printf0V*.delete lastnV1E
printf0VW.delete middlenV1Eprintf0Venter your choiceV1E
scanf0VPdV,Qa1E
switch0a1
case %:
create01Edisplay01EbreakEcase 8:display01EbreakEcase 5:insfirst01E '5
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
63/91
http://vustudents.ning.com
http://vustudents.ning.com
display01E
breakEcase ?:
inslast01Edisplay01E
breakE
case @:insmiddle01E
display01E
breakE
case ':
delfirst01E
display01EbreakE
case *:
dellast01E
display01EbreakE
case W:
delmiddle01E
display01EbreakE
case &:
e4it0>1E
S
printf0Vndo you want to continue0%/>1nV1E
scanf0VPdV,Qs1ES
while0sJJ%1ES
create01
int sE
sJsi
-
8/11/2019 CS301 Notes
64/91
http://vustudents.ning.com
http://vustudents.ning.com
previousJprevious-HlinkE
Sprevious-HlinkJfirstE
previousJfirstEreturn0>1E
S
display01
if0headJJnull1
printf0Vnull firstV1E
else
tempJheadEwhile0tempTJnull1
printf0VPd-HV,temp-Hdata1E
tempJtemp-HlinkES
printf0VnullnV1E
return0>1E
S
insfirst01
int sE
if 0headJJnull1
printf0Vlist is nullV1E
else
sJsi1E
Sdelfirst01int sEif0headJJnull1printf0Vlist is nullV1EelseheadJhead-HlinkE '@
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
65/91
http://vustudents.ning.com
http://vustudents.ning.com
return0>1E
Sinslast01
int sE
struct node Utemp,UlastE
if 0headJJnull1
printf0Vlist is nullV1E
else
sJsi1ES
dellast01
int s,mE
struct node Upre,Une4tEif0headJJnull1
printf0Vlist is nullV1Eelse
ne4tJheadEne4tJhead-HlinkE
preJheadE
while0ne4t-HlinkTJnull1
ne4tJne4t-HlinkE
preJpre-HlinkESpre-HlinkJne4t-HlinkESreturn0>1ESinsmiddle01 ''
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
66/91
-
8/11/2019 CS301 Notes
67/91
http://vustudents.ning.com
http://vustudents.ning.com
countJ8E
printf0Venter the position of the elementV1Escanf0VPdV,Qf1E
while00countGf1 QQ 0ne4t-HlinkTJnull11
ne4tJne4t-HlinkE
preJpre-HlinkEcountJcountR%E
S
if00countGf1 QQ 0ne4t-HlinkJJnull11
printf0Vnot possible to insert. the list is contains Pd elementsV,count1E
Spre-HlinkJne4t-HlinkE
S
return0>1ES
Ex& No& 8 ,ou!"y "in9e, "ist
ProgramB
8& rite a C #rogram to im#"ement t+e Dou!"e .in9e, .ist&
FincludeGconio.hH
FincludeGstdio.hHFincludeGstdlib.hH
struct student
int rollnoEstruct student UprevE
struct student Une4tE
SE
typedef struct student listE
void add0list Uhead,int rollno1list UnewZelt,UtempJheadEnewZeltJ0list U1malloc0si
-
8/11/2019 CS301 Notes
68/91
http://vustudents.ning.com
http://vustudents.ning.com
while0temp-Hne4tTJ!1
tempJtemp-Hne4tEnewZelt-HprevJtempE
temp-Hne4tJnewZeltES
void insert0list Uhead,int rollno,int position1
int iE
list UnewZelt,UadBZelt,UtempJheadE
newZeltJ0list U1malloc0si,iJ%EE
while0tempTJ!1
if0temp-HrollnoJJrollno1
foundJiE
breakE
S
iRRE
tempJtemp-Hne4tE
Sreturn foundESvoid remove7lt0list Uhead,int rollno1list UdelZelt,Usuccessor,Upredecsor,UtempJhead-Hne4tEint i,foundEfoundJfind0head,rollno1E '&
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
69/91
http://vustudents.ning.com
http://vustudents.ning.com
if0foundTJ>1
while0temp-HrollnoTJrollno1
tempJtemp-Hne4tEdelZeltJtempE
predecsorJdelZelt-HprevEsuccessorJdelZelt-Hne4tE
predecsor-Hne4tJdelZelt-Hne4tE
successor-HprevJdelZelt-HprevE
free0delZelt1E
printf0Vn#ne 7lement is deletedV1ES
else
printf0Vn7lement has not ;oundTCann]t perform )eletionTV1E
Svoid printZlist0list Uhead1
if0head-Hne4tTJ!1
list UtempJhead-Hne4tEprintf0Vnhe ist:nV1E
while0tempTJ!1
printf0VPd-- H V,temp-Hrollno1E
tempJtemp-Hne4tE
Sprintf0V!ullV1E
Selse
printf0Vn he ist is 7mptyV1E
Svoid makeZemptylist0list Uhead1
head-HprevJ!E
head-Hne4tJ!E
printf0Vnhe ist has been deletedT V1E
Svoid main01list UheadEint position,rollno,optionEheadJ0list U1malloc0si
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
70/91
http://vustudents.ning.com
http://vustudents.ning.com
head-Hne4tJ!E
clrscr01Ewhile0%1
printf0Vnn%.+ddn8.Insert a Itemn5.2emove a Itemn?.;indn@.(rint
the
istn'.)elete the istn*.74itV1Eprintf0Vn7nter your Choice:V1E
scanf0VPdV,Qoption1E
switch0option1
case %:
printf0Vn7nter 2ollno of the !ew 7lement:V1Escanf0VPdV,Qrollno1E
add0head,rollno1E
breakE
case 8:printf0Vn7nter 2ollno of 7lement to be Inserted:V1E
scanf0VPdV,Qrollno1E
printf0Vn7nter (osition to insert:V1E
scanf0VPdV,Qposition1E
insert0head,rollno,position1EbreakE
case 5:
printf0Vn7nter the 2ollno of the element to 2emoved:V1E
scanf0VPdV,Qrollno1E
remove7lt0head,rollno1E
breakEcase ?:
printf0V7nter rollno of Item to be found:V1Escanf0VPdV,Qrollno1E
positionJfind0head,rollno1E
if0positionTJ>1printf0Vn7lement has been foundT(ositionJPdV,position1E
else
printf0Vn7lement has not found in the istTV1E
breakE
case @:
printZlist0head1EbreakEcase ':makeZemptylist0head1EbreakEcase *:e4it0>1ES *%
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
71/91
http://vustudents.ning.com
http://vustudents.ning.com
S getch01E S
7 x& NoB ; Circu"ar Sing"y .in9e, "ist
Program B
FincludeGstdio.hH
FincludeGconio.hH
int a,sE
struct node
int dataE
struct node UlinkE
SEstruct node Uhead,Ufirst,Uprevious,Ulast,UtempE
void main01
firstJ!E
headJ!EpreviousJ!E
clrscr01E
do
printf0V%.creationnV1Eprintf0V8.displaynV1E
printf0V5.insert firstnV1Eprintf0V?.insert lastnV1E
[email protected] middlenV1E
printf0V'.delete firstnV1Eprintf0V*.delete lastnV1E
printf0VW.delete middlenV1E
printf0Venter your choiceV1E
scanf0VPdV,Qa1E
switch0a1
case %:create01Edisplay01EbreakEcase 8:display01EbreakE *8
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
72/91
http://vustudents.ning.com
http://vustudents.ning.com
case 5:
insfirst01Edisplay01E
breakE
case ?:inslast01E
display01E
breakE
case @:
insmiddle01E
display01EbreakE
case ':
delfirst01E
display01EbreakE
case *:
dellast01E
display01E
breakEcase W:
delmiddle01E
display01E
breakE
case &:
e4it0>1ES
printf0Vndo you want to continue0%/>1nV1Escanf0VPdV,Qs1E
S
while0sJJ%1ES
create01
int sE
sJsi
-
8/11/2019 CS301 Notes
73/91
http://vustudents.ning.com
http://vustudents.ning.com
previousJfirstE
Selse
previousJheadE
while0previous-Hlink TJhead1
previousJprevious-HlinkEprevious-HlinkJfirstE
previousJfirstE
S
lastJfirstE
return0>1E
S
display01
if0headJJ!1printf0Vlist is nullV1E
else
tempJheadE
while0tempTJlast1
printf0VPd-HV,temp-Hdata1E
tempJtemp-HlinkE
S
if0tempJJlast1
printf0VPd -HV,temp-Hdata1E
tempJtemp-HlinkES
S
return0>1E
S
insfirst01
int sEif 0headJJ!1printf0Vlist is nullV1EelsesJsi
-
8/11/2019 CS301 Notes
74/91
http://vustudents.ning.com
http://vustudents.ning.com
printf0Venter datanV1E
scanf0VPdV,Qtemp-Hdata1Etemp-HlinkJheadE
headJtempEfirstJtempE
last-HlinkJtempE
Sreturn0>1E
S
delfirst01
int sEif0headJJ!1
printf0Vlist is nullV1E
else
headJhead-HlinkElast-HlinkJheadE
if0last-HlinkJJhead1
headJ!E
return0>1E
S
inslast01
int sE
struct node Ulast%,Ufirst%E
if 0headJJ!1
printf0Vlist is nullV1Eelse
sJsi1ES *@
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
75/91
http://vustudents.ning.com
http://vustudents.ning.com
dellast01
int s,mEstruct node Upre,Une4tE
if0headJJ!1
printf0Vlist is nullV1Eelse
if0headJJlast1
headJlastJ!E
else
ne4tJheadE
while0ne4t-HlinkTJlast1
ne4tJne4t-HlinkE
ne4t-HlinkJheadE
lastJne4tE
S
S
return0>1ES
insmiddle01
int s,f,countE
struct node Une4t,Upre,Une4E
if 0headJJ!1printf0Vlist is nullV1E
else
sJsi
-
8/11/2019 CS301 Notes
76/91
http://vustudents.ning.com
http://vustudents.ning.com
if00countGf1 QQ 0ne4t-HlinkJJhead11
printf0Vnot possible to insert. the list is contains Pd elementsV,count1E
Selse
pre-HlinkJne4Ene4-HlinkJne4tE
S
S
return0>1E
Sdelmiddle01
int s,f,countE
struct node Une4t,Upre,Une4Eif 0headJJ!1
printf0Vlist is nullV1E
else
sJsi1ES **
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
77/91
http://vustudents.ning.com
http://vustudents.ning.com
Ex& NoB < O#erations On inary Trees
Program B
FincludeGstdio.hH
FincludeGmalloc.hH
struct node
int dataEstruct node UlchildE
struct node UrchildE
S
void creation01
printf0Vn 7nter the value of the root node nV1E
tJ0struct nodeU1malloc0si1
if0a-HdataHn1insert0n,a-Hlchild1E
else
insert0n,a-Hrchild1ES
4J0struct nodeU1 malloc0si
-
8/11/2019 CS301 Notes
78/91
http://vustudents.ning.com
http://vustudents.ning.com
else
if0a-HrchildJJ!1
a-HrchildJ4E
a-Hrchild-HlchildJ!Ea-Hrchild-HrchildJ!E
S
S
void inorder0struct nodeU a1
if0aTJ!1
inorder0a-Hlchild1E
printf0V P%>d V,a-Hdata1Einorder0a-Hrchild1E
S
S
void preorder0struct node Ua1
if0aTJ!1
printf0V P%>dV,a-Hdata1 E
preorder0a-Hlchild1E
preorder0a-Hrchild1E
SS
void postorder0struct node Ua1
if0aTJ!1
postorder0a-Hlchild1E
postorder0a-Hrchild1E
printf0V P%>dV,a-Hdata1E
S
S
void main01int num,cEclrscr01Ecreation01Edoprintf0Vn %. Insertion n8. Inorder n5. preorder n?.postorder V1Eprintf0Vn for e4it give choice greater than fourV1E*&
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
79/91
http://vustudents.ning.com
http://vustudents.ning.com
printf0V n7nter your choice V1E
scanf0VPdV,Qc1Eswitch0c1
case %:printf0V n )ata to be inserted V1E
scanf0VPdV,Qnum1E
insert0num,t1EbreakE
case 8: inorder0t1E
breakE
case 5: preorder0t1E
breakE
case ?: postorder0t1EbreakE
S
Swhile0cG@1E
S
Ex& No& = !inary tree o#eration
ProgramB*. rite a C program to implement the binary tree operations A insert,
delete, and search.
FincludeGconio.hH
FincludeGstdio.hH
FincludeGstdlib.hH
struct bstree
int dataE
struct bstree UleftEstruct bstree UrightE
SE
struct bstree Uroot,UtempE
struct bstreeU insertbst0struct bstree Uroot,int 41
if0 root JJ !1rootJmalloc0si
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
80/91
http://vustudents.ning.com
http://vustudents.ning.com
else if04 G root-Hdata1
root-HleftJinsertbst0root-Hleft,41Eelse if04 H root-Hdata1
root-HrightJinsertbst0root-Hright,41Ereturn rootE
S
struct bstreeU findMin0struct bstree Ut1
if0tJJ!1
return !E
else
if0t-Hleft TJ !1return findMin0t-Hleft1E
else
return tE
Sstruct bstreeU findMa40struct bstree Ut1
if0tJJ!1
return !E
elseif0t-Hright TJ !1
return findMa40t-Hright1E
else
return tE
S
int find0struct bstree Utemp,int key1
if 0tempJJ!1
return !ES
else
if0key G temp-Hdata1
return find0temp-Hleft,key1E
else if 0key H temp-Hdata1return find0temp-Hright,key1Eelsereturn tempESSint findZmin0struct bstree Utemp1 W%
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
81/91
http://vustudents.ning.com
http://vustudents.ning.com
if0temp-Hleft JJ !1
return temp-HdataEelse
return findZmin0temp-Hleft1E
S
int findZma40struct bstree Utemp1
if0temp-Hright JJ !1
return temp-HdataE
else
return findZma40temp-Hright1E
S
struct bstreeU remove7lt0struct bstree Ut,int key1
struct bstree UtempE
if 0tJJ!1
printf0Vn!ode is not availableV1E
else if0key G t-Hdata1t-HleftJremove7lt0t-Hleft,key1E
else if0key H t-Hdata1
t-HrightJremove7lt0t-Hright,key1E
else if0t-Hleft TJ ! QQ t-Hright TJ !1
tempJfindMin0t-Hright1Et-HdataJtemp-HdataE
t-HrightJremove7lt0t-Hright,t-Hdata1ES
else
tempJtE
if0t-HleftJJ!1
tJt-HrightE
else if0t-HrightJJ!1
tJt-HleftE
free0temp1ESreturn tESvoid printZlist0struct bstree Uroot1if0rootTJ!1 W8
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
82/91
http://vustudents.ning.com
http://vustudents.ning.com
if0root-Hleft TJ !1
printZlist0root-Hleft1E
printf0V PdV,root-Hdata1E
if0root-Hright TJ !1
printZlist0root-Hright1ES
S
void main01
struct bstree UnewZeltE
int option,rollno,infoE
rootJ!Eclrscr01E
while0%1
printf0Vnn%.Insert a Itemn8.2emove a Itemn5.;indn?.;ind Minimumaluen@.;ind Ma4imum aluen'.(rint the istn*.74itV1E
printf0Vn7nter your Choice:V1E
scanf0VPdV,Qoption1E
switch0option1
case %:printf0Vn7nter 2ollno of 7lement to be Inserted:V1E
scanf0VPdV,Qrollno1ErootJinsertbst0root,rollno1E
breakE
case 8:printf0Vn7nter the 2ollno of the element to 2emoved:V1E
scanf0VPdV,Qrollno1E
rootJremove7lt0root,rollno1E
breakE
case 5:
printf0V7nter rollno of Item to be found:V1Escanf0VPdV,Qrollno1EinfoJfind0root,rollno1Eif0infoTJ>1printf0Vn7lement has been foundT at (ositionJPdV,info1Eif0info JJ >1printf0Vn7lement has not found in the istTV1EW5
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
83/91
http://vustudents.ning.com
http://vustudents.ning.com
breakE
case ?:
if0root JJ !1printf0Vnree is emptyV1E
else
infoJfindZmin0root1E
printf0Vn he Minimum alue is:PdV,info1E
S
breakE
case @:
if0root JJ !1printf0Vnree is emptyV1E
else
infoJfindZma40root1Eprintf0Vn he Ma4imum alue is:PdV,info1E
S
breakE
case ':
if0root JJ !1printf0Vnree is emptyV1E
else
printZlist0root1E
breakE
case *:
e4it0>1ES
Sgetch01E
S
Ex& No& > uic9 Sort
ProgramB
Finclude Gstdio.hH
FincludeGconio.hHint n,aK5>L,passJ%Evoid 6uicksort0int low, int high1if0lowGhigh1int k,iEkJpartition0low,high1E W?
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
84/91
http://vustudents.ning.com
http://vustudents.ning.com
printf0Vpass PdnV,passRR1E
for0iJ%EiGJnEiRR1printf0VP'dV,aKiL1E
printf0VnV1E6uicksort0low,k-%1E
6uicksort0kR%,high1E
SS
int partition0int low,int high1
int v,i,tE
vJaKlowLE
iJlowEdo
while0aKiLGJv1
iRREwhile0aKhighLHv1
high--E
if0iGhigh1
tJaKiLEaKiLJaKhighLE
aKhighLJtE
S
S
while0iGhigh1E
aKlowLJaK highLEaKhighLJvE
return highES
void main01
int low,high,iE
clrscr01E
printf0V 7nter the array si
-
8/11/2019 CS301 Notes
85/91
http://vustudents.ning.com
http://vustudents.ning.com
Ex& No& ? Hea# Sort
ProgramB
FincludeGconio.hHFincludeGstdio.hH
int 4K8>L,n,n%E
void heapsort01E
void adBust01E
void heapify01E
void main01
int iE
clrscr01E
printf0V7!72 37 !#. #; 77M7!$ :V1Escanf0VPdV,Qn1E
n%JnE
printf0O7!72 37 77M7!$ nN1E
for0iJ%EiGJnEiRR1
scanf0VPdV,Q4KiL1Eclrscr01E
printf0V n +22+D 7;#27 $#2 :V1E
for0iJ%EiGJnEiRR1
printf0VPdtV,4KiL1E
heapsort01E
getch01ES
void heapsort01
int i,t,BEheapify01E
for0iJnEiHJ8Ei--1
tJ4KiLE
4KiLJ4K%LE4K%LJtEadBust0%,i-%1Eprintf0Vnpass Pd nV,n-0i-%11Efor0BJ%EBGJn%EBRR1printf0V PdtV,4KBL 1E W'
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
86/91
http://vustudents.ning.com
http://vustudents.ning.com
S
Svoid adBust0int i,int n1
int BE
int tE
BJ8UiEtJ4KiLE
while0BGJn1
if0BGn QQ 4KBL G 4KBR%L1
BRRE
if0tHJ4KBL1breakE
4KB/8LJ4K BLE
BJ8UBE
S4KB/8LJtE
S
void heapify01
int i,BE
for0iJn/8EiHJ%Ei--1
adBust0i,n1E
S
Ex& No& 1@ De#t+ first searc+
ProgramB
%>. rite a C program to implement the )epth ;irst $earch.
FincludeGconio.hH
FincludeGstdio.hH
int graphK%>LK%>LE
int visitedK%>LE
void IntiliE W*
http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/http://vustudents.ning.com/ -
8/11/2019 CS301 Notes
87/91
http://vustudents.ning.com
http://vustudents.ning.com
S
S
void printZgraph0int noZv1
int i,BE
printf0Vnhe 9raph0Matri4 2epresentation1:nV1Efor0iJ%EiGJnoZvEiRR1
printf0VtPdV,i1E
for0iJ%EiGJnoZvEiRR1
printf0VnPdV,i1E
for0BJ%EBGJnoZvEBRR1
printf0VtPdV,graphKiLKBL1E
S
SS
void );$0int startZv,int noZv1
int iEvisitedKstartZvLJ%E
printf0VPd-- HV,startZv1E
for0iJ%EiGJnoZvEiRR1