Data structure

55
06/06/22 06/06/22 1 Concept of Data Concept of Data Structure Structure Data Structure: Data Structure: A means of storing a collection of A means of storing a collection of data. data. OR OR It is the specification of the It is the specification of the elements of the structure, the elements of the structure, the relationships between them, and the relationships between them, and the operation that may be performed operation that may be performed upon them. upon them.

description

 

Transcript of Data structure

Page 1: Data structure

040823040823 11

Concept of Data StructureConcept of Data Structure

Data StructureData Structure

A means of storing a collection of dataA means of storing a collection of data

OROR

It is the specification of the elements of the It is the specification of the elements of the structure the relationships between them and structure the relationships between them and the operation that may be performed upon them the operation that may be performed upon them

040823040823 22

Computer Science amp Data Computer Science amp Data StructureStructure

Computer science is concern with study of Computer science is concern with study of Methods for effectively using a computer to Methods for effectively using a computer to solve problemssolve problems

ororIn determining exactly the problem to be solvedIn determining exactly the problem to be solvedThis process entailsThis process entails11 Gaining an understanding of the problemGaining an understanding of the problem

22 Translating vague descriptions goals and contradictory Translating vague descriptions goals and contradictory requests and often unstated desires into a precisely requests and often unstated desires into a precisely formulated conceptual Solutionformulated conceptual Solution

040823040823 33

Computer Science amp Data Structure Computer Science amp Data Structure (Continue)(Continue)

33 Implementing the solutionImplementing the solution with a computer with a computer program This solution typically consists of program This solution typically consists of two parts two parts algorithms and data structuresalgorithms and data structures

AlgorithmAlgorithmAn algorithm is a concise specification of a methodAn algorithm is a concise specification of a method for solving a problemfor solving a problemData StructureData StructureA data structure can be viewed as consisting of a set A data structure can be viewed as consisting of a set of algorithms for performing operations on the dataof algorithms for performing operations on the data it stores it stores

040823040823 44

Computer Science amp Data Structure Computer Science amp Data Structure (Continue)(Continue)

Data Structure amp AlgorithmData Structure amp Algorithm

Algorithms are part of what constitutesAlgorithms are part of what constitutes

a data structure In constructing a solution toa data structure In constructing a solution to

a problem a data structure must be chosen a problem a data structure must be chosen

that allows the data to be operated upon that allows the data to be operated upon

easily in the manner required by the easily in the manner required by the

algorithmalgorithm

040823040823 55

12 Data Structures vs Algorithms

bullChoice of data structures 1048708A primary design consideration at many times 1048708Determines the algorithms to be used 1048708ldquoA well-designed data structure allows a variety of critical operations to be

performed using as few resources both execution time and memory space as possiblerdquo

bullThe opposite direction sometimes 1048708Certain algorithms require particular data structures 1048708Eg shortest path algorithm needs priority queues

ndash Data Structuresndash How do we organize ndash the data to be ndash handled

Algorithms Describe the process by which data is handledDuality

040823040823 66

040823040823 77

Abstract Data Types(ADT)Abstract Data Types(ADT)

What is AbstractionWhat is AbstractionTo abstract is to ignore some detailsTo abstract is to ignore some detailsof a thing in favor of othersof a thing in favor of others

ADT amp Data structureADT amp Data structureAn An Abstract Data TypeAbstract Data Type (ADT) is more a way of (ADT) is more a way of

looking at a data structure focusing on what it looking at a data structure focusing on what it does and ignoring how it does its job does and ignoring how it does its job

040823040823 88

Abstract Data Types(ADT)Abstract Data Types(ADT)

Why need AbstractionWhy need AbstractionAbstraction is important in problem solving because Abstraction is important in problem solving because it allows problem solvers to focus on essential details it allows problem solvers to focus on essential details while ignoring the inessential thus simplifying the while ignoring the inessential thus simplifying the problem and bringing to attention those aspects of the problem and bringing to attention those aspects of the problem involved in its solution Once an abstract problem involved in its solution Once an abstract data type is understood and documented it serves as a data type is understood and documented it serves as a specification that programmers can use to guide their specification that programmers can use to guide their choice of data representation and operation choice of data representation and operation implementation and as a standard for ensuring implementation and as a standard for ensuring program correctness program correctness

040823040823 99

Abstract Data Types(ADT)Abstract Data Types(ADT)Abstract data typesAbstract data typesEach data structure can be developed around the Each data structure can be developed around the concept of an abstract data type that defines both dataconcept of an abstract data type that defines both dataorganization and data handling operationsorganization and data handling operations A mathematical entity consisting of a set of values A mathematical entity consisting of a set of values

and a collection of operations that manipulate them and a collection of operations that manipulate them For example the Integer abstract data type consists of For example the Integer abstract data type consists of a carrier set containing the positive and negative a carrier set containing the positive and negative whole numbers and 0 and a collection of operations whole numbers and 0 and a collection of operations manipulating these values such as addition manipulating these values such as addition subtraction multiplication equality comparison and subtraction multiplication equality comparison and order comparisonorder comparison

040823040823 1010

Abstract Data Types(ADT)Abstract Data Types(ADT) Abstract data types are important in computer science Abstract data types are important in computer science

because they provide a clear and precise way to because they provide a clear and precise way to specify what data a program must manipulate and specify what data a program must manipulate and how the program must manipulate its data without how the program must manipulate its data without regard to details about how data are represented or regard to details about how data are represented or how operations are implementedhow operations are implemented

ADT defines both data organization and data ADT defines both data organization and data handling operations handling operations

The study of data structure is organized around a The study of data structure is organized around a collection of abstract data types that includes lists collection of abstract data types that includes lists trees sets graphs and dictionaries trees sets graphs and dictionaries

040823040823 1111

Abstract Data Types(ADT)Abstract Data Types(ADT)

ADT is not a part of a program since a ADT is not a part of a program since a program written in a programming language program written in a programming language requires the definition of data structure not requires the definition of data structure not just the operations on the data structurejust the operations on the data structure

ADT is a useful tool for specifying the logical ADT is a useful tool for specifying the logical properties of a data typeproperties of a data type

ADT is not concerned with the timespace ADT is not concerned with the timespace efficiency of data typeefficiency of data type

040823040823 1212

Specification of ADTSpecification of ADT

ADT consist of 2 partsADT consist of 2 parts11 Value DefinitionValue Definition

22 Operator DefinitionOperator Definition

040823040823 1313

Specification of ADTSpecification of ADT

11 Value DefinitionValue DefinitionIt defines the collection of values for the It defines the collection of values for the ADT and consist of two partsADT and consist of two partsa)a) Definition Clause Definition Clause b)b) Condition ClauseCondition Clause eg For ADT RATIONAL eg For ADT RATIONAL Value definition it states that RATIONAL value Value definition it states that RATIONAL value consist of two integers the second of which does not equal consist of two integers the second of which does not equal to zeroto zeroThe keyword The keyword abstract typedefabstract typedef introduce a value definition introduce a value definition

040823040823 1414

Specification of ADTSpecification of ADT

Condition ClauseCondition Clause Used to specify any conditions on the newly defined Used to specify any conditions on the newly defined

typetype The keyword The keyword condition condition is used to specify any is used to specify any

conditions on the newly defined typeconditions on the newly defined typeFor eg for RATIONAL ADTFor eg for RATIONAL ADTCondition Clause denominator may not be zeroCondition Clause denominator may not be zeroNote The definition clause is required but the Note The definition clause is required but the condition clause may not be necessary for every condition clause may not be necessary for every ADTADT

040823040823 1515

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator Definition It defines the operations that are to be It defines the operations that are to be

performed on a data setperformed on a data set Each operator is defined as an abstract Each operator is defined as an abstract

function with three partsfunction with three parts HeaderHeader Optional preconditions Optional preconditions Post conditions Post conditions

040823040823 1616

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator DefinitionFor eg Operator definition for RATIONAL ADTFor eg Operator definition for RATIONAL ADT includes the operations of creation addition includes the operations of creation addition multiplication and equalitymultiplication and equality Now for multiplication operation the operator definition for Now for multiplication operation the operator definition for

RATIONAL ADT isRATIONAL ADT is Abstract RATIONAL mult(ab)helliphellipAbstract RATIONAL mult(ab)helliphellipheaderheader

RATIONAL a b helliphelliphellip RATIONAL a b helliphelliphellip header headermul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip mul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip postcondpostcond

mul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellipmul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellippostcondpostcond

040823040823 1717

Complete example of RATIONL Complete example of RATIONL ADTADT

value definition value definition Abstract typedefAbstract typedeflt int int gtRATIONALlt int int gtRATIONAL ConditionCondition RATIONAL[1]=0 RATIONAL[1]=0 Operator definition Operator definition Abstract equal(ab)Abstract equal(ab) RATIONAL a bRATIONAL a b Postcondition equal==(a[0]b[1]==b[0]b[1])Postcondition equal==(a[0]b[1]==b[0]b[1]) Like this we can declare the other operationsLike this we can declare the other operations

040823040823 1818

Classification of Data StructureClassification of Data Structure

Linear and Non-LinearLinear and Non-Linear

In linear data structure the data items are arranged In linear data structure the data items are arranged in linear sequence eg Array Stack Queue Linked in linear sequence eg Array Stack Queue Linked ListList

In non-linear data items are not in sequence eg In non-linear data items are not in sequence eg Tree graph HeapTree graph Heap

040823040823 1919

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Homogenous and Non-homogenousHomogenous and Non-homogenous

In homogenous data structure all the elements are In homogenous data structure all the elements are of same type eg Arrayof same type eg Array

In non-homogenous data structure the elements In non-homogenous data structure the elements may or may not be of same type eg Recordmay or may not be of same type eg Record

040823040823 2020

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Primitive and Non-PrimitivePrimitive and Non-PrimitivePrimitive data structures constitute thePrimitive data structures constitute thenumber and the characters which are builtnumber and the characters which are builtprograms examples int realspointer programs examples int realspointer datacharaters data logical data datacharaters data logical data

040823040823 2121

What is STACK or Pushdown What is STACK or Pushdown ListList

A ordered collection of items A ordered collection of items into which new items may be into which new items may be inserted and from which items inserted and from which items may be deleted at one end may be deleted at one end called the top of stack called the top of stack

040823040823 2222

Operations on STACKOperations on STACK

PUSHWhen item is added in stackPUSHWhen item is added in stack POPWhen item is removed from POPWhen item is removed from

stackstack EMPTYStack containing no itemsEMPTYStack containing no items StackTopDetermine what the top StackTopDetermine what the top

item on a stack without removing item on a stack without removing itthis is a combination of push amp popitthis is a combination of push amp pop

040823040823 2323

Push amp Pop in STACKPush amp Pop in STACK PUSH OperationPUSH Operation PUSHPUSH(STACK TOPMAXITEM) (STACK TOPMAXITEM) STACK--STACK--Name given to ArrayName given to Array TOP----TOP----It contains the location of top It contains the location of top

elementselements MAX---MAX---It is maximum size of STACKIt is maximum size of STACK ITEM---gtValue that is to be store in stack ITEM---gtValue that is to be store in stack

ifif top = MAX top = MAX thenthen stackfull stackfull top = top+1 top = top+1 stack(top) = item stack(top) = item ReturnReturn

040823040823 2424

Push amp Pop in STACKPush amp Pop in STACK

POP OperationPOP Operation

POPPOP(STACK TOPITEM) (STACK TOPITEM)

ifif top = 0 top = 0 thenthen Underflow Underflow item = stack(top) item = stack(top) top = top-1 top = top-1 Return Return

040823040823 2525

Applications of STACKApplications of STACK

Expression EvaluationExpression EvaluationParenthesis CheckerParenthesis CheckerRecursionRecursion

040823040823 2626

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

Operator preecedenceOperator preecedence^ ---------Higher precedence^ ---------Higher precedence--------Next Precedence--------Next Precedence+_-------Least precedence+_-------Least precedence

040823040823 2727

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

The rules to rememberThe rules to remember

11 Parenthesize the expression Parenthesize the expression starting fro left to rightstarting fro left to right

22 During Parenthesizing the During Parenthesizing the

expression the operands associatedexpression the operands associated

with operator having higher with operator having higher

precedence are first parenthesizedprecedence are first parenthesized

040823040823 2828

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

33 The sub-expression which has been The sub-expression which has been converted into postfix is to be converted into postfix is to be treated as single operandtreated as single operand

44 Once the expression is converted to Once the expression is converted to postfix form remove the postfix form remove the parenthesis parenthesis

Example A+BCExample A+BC A+[(B+C)+(D+E)F]GA+[(B+C)+(D+E)F]G Answer ABC+DE+F+G+Answer ABC+DE+F+G+

040823040823 2929

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

Postfix(QP)Postfix(QP) QmdashgtGiven Infix expressionQmdashgtGiven Infix expression P-gtEquivalent Postfix expressionP-gtEquivalent Postfix expression

11 Push ldquo(ldquo onto STACK and add ldquo)rdquo to the Push ldquo(ldquo onto STACK and add ldquo)rdquo to the end of Qend of Q

22 Scan Q from left to right and repeat step 3 Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK to 6 for each element of Q until the STACK is Emptyis Empty

33 If an operand is encountered add it to PIf an operand is encountered add it to P44 If a left parenthesis is encountered push If a left parenthesis is encountered push

it onto STACK it onto STACK

040823040823 3030

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

55 If an operator reg is encountered If an operator reg is encountered thenthen

(a) ADD reg to STACK(a) ADD reg to STACK

[End of IF][End of IF]

(b) Repeatedly pop from STACK and (b) Repeatedly pop from STACK and add P each operator which has add P each operator which has same precedence as or higher same precedence as or higher precedence than regprecedence than reg

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 2: Data structure

040823040823 22

Computer Science amp Data Computer Science amp Data StructureStructure

Computer science is concern with study of Computer science is concern with study of Methods for effectively using a computer to Methods for effectively using a computer to solve problemssolve problems

ororIn determining exactly the problem to be solvedIn determining exactly the problem to be solvedThis process entailsThis process entails11 Gaining an understanding of the problemGaining an understanding of the problem

22 Translating vague descriptions goals and contradictory Translating vague descriptions goals and contradictory requests and often unstated desires into a precisely requests and often unstated desires into a precisely formulated conceptual Solutionformulated conceptual Solution

040823040823 33

Computer Science amp Data Structure Computer Science amp Data Structure (Continue)(Continue)

33 Implementing the solutionImplementing the solution with a computer with a computer program This solution typically consists of program This solution typically consists of two parts two parts algorithms and data structuresalgorithms and data structures

AlgorithmAlgorithmAn algorithm is a concise specification of a methodAn algorithm is a concise specification of a method for solving a problemfor solving a problemData StructureData StructureA data structure can be viewed as consisting of a set A data structure can be viewed as consisting of a set of algorithms for performing operations on the dataof algorithms for performing operations on the data it stores it stores

040823040823 44

Computer Science amp Data Structure Computer Science amp Data Structure (Continue)(Continue)

Data Structure amp AlgorithmData Structure amp Algorithm

Algorithms are part of what constitutesAlgorithms are part of what constitutes

a data structure In constructing a solution toa data structure In constructing a solution to

a problem a data structure must be chosen a problem a data structure must be chosen

that allows the data to be operated upon that allows the data to be operated upon

easily in the manner required by the easily in the manner required by the

algorithmalgorithm

040823040823 55

12 Data Structures vs Algorithms

bullChoice of data structures 1048708A primary design consideration at many times 1048708Determines the algorithms to be used 1048708ldquoA well-designed data structure allows a variety of critical operations to be

performed using as few resources both execution time and memory space as possiblerdquo

bullThe opposite direction sometimes 1048708Certain algorithms require particular data structures 1048708Eg shortest path algorithm needs priority queues

ndash Data Structuresndash How do we organize ndash the data to be ndash handled

Algorithms Describe the process by which data is handledDuality

040823040823 66

040823040823 77

Abstract Data Types(ADT)Abstract Data Types(ADT)

What is AbstractionWhat is AbstractionTo abstract is to ignore some detailsTo abstract is to ignore some detailsof a thing in favor of othersof a thing in favor of others

ADT amp Data structureADT amp Data structureAn An Abstract Data TypeAbstract Data Type (ADT) is more a way of (ADT) is more a way of

looking at a data structure focusing on what it looking at a data structure focusing on what it does and ignoring how it does its job does and ignoring how it does its job

040823040823 88

Abstract Data Types(ADT)Abstract Data Types(ADT)

Why need AbstractionWhy need AbstractionAbstraction is important in problem solving because Abstraction is important in problem solving because it allows problem solvers to focus on essential details it allows problem solvers to focus on essential details while ignoring the inessential thus simplifying the while ignoring the inessential thus simplifying the problem and bringing to attention those aspects of the problem and bringing to attention those aspects of the problem involved in its solution Once an abstract problem involved in its solution Once an abstract data type is understood and documented it serves as a data type is understood and documented it serves as a specification that programmers can use to guide their specification that programmers can use to guide their choice of data representation and operation choice of data representation and operation implementation and as a standard for ensuring implementation and as a standard for ensuring program correctness program correctness

040823040823 99

Abstract Data Types(ADT)Abstract Data Types(ADT)Abstract data typesAbstract data typesEach data structure can be developed around the Each data structure can be developed around the concept of an abstract data type that defines both dataconcept of an abstract data type that defines both dataorganization and data handling operationsorganization and data handling operations A mathematical entity consisting of a set of values A mathematical entity consisting of a set of values

and a collection of operations that manipulate them and a collection of operations that manipulate them For example the Integer abstract data type consists of For example the Integer abstract data type consists of a carrier set containing the positive and negative a carrier set containing the positive and negative whole numbers and 0 and a collection of operations whole numbers and 0 and a collection of operations manipulating these values such as addition manipulating these values such as addition subtraction multiplication equality comparison and subtraction multiplication equality comparison and order comparisonorder comparison

040823040823 1010

Abstract Data Types(ADT)Abstract Data Types(ADT) Abstract data types are important in computer science Abstract data types are important in computer science

because they provide a clear and precise way to because they provide a clear and precise way to specify what data a program must manipulate and specify what data a program must manipulate and how the program must manipulate its data without how the program must manipulate its data without regard to details about how data are represented or regard to details about how data are represented or how operations are implementedhow operations are implemented

ADT defines both data organization and data ADT defines both data organization and data handling operations handling operations

The study of data structure is organized around a The study of data structure is organized around a collection of abstract data types that includes lists collection of abstract data types that includes lists trees sets graphs and dictionaries trees sets graphs and dictionaries

040823040823 1111

Abstract Data Types(ADT)Abstract Data Types(ADT)

ADT is not a part of a program since a ADT is not a part of a program since a program written in a programming language program written in a programming language requires the definition of data structure not requires the definition of data structure not just the operations on the data structurejust the operations on the data structure

ADT is a useful tool for specifying the logical ADT is a useful tool for specifying the logical properties of a data typeproperties of a data type

ADT is not concerned with the timespace ADT is not concerned with the timespace efficiency of data typeefficiency of data type

040823040823 1212

Specification of ADTSpecification of ADT

ADT consist of 2 partsADT consist of 2 parts11 Value DefinitionValue Definition

22 Operator DefinitionOperator Definition

040823040823 1313

Specification of ADTSpecification of ADT

11 Value DefinitionValue DefinitionIt defines the collection of values for the It defines the collection of values for the ADT and consist of two partsADT and consist of two partsa)a) Definition Clause Definition Clause b)b) Condition ClauseCondition Clause eg For ADT RATIONAL eg For ADT RATIONAL Value definition it states that RATIONAL value Value definition it states that RATIONAL value consist of two integers the second of which does not equal consist of two integers the second of which does not equal to zeroto zeroThe keyword The keyword abstract typedefabstract typedef introduce a value definition introduce a value definition

040823040823 1414

Specification of ADTSpecification of ADT

Condition ClauseCondition Clause Used to specify any conditions on the newly defined Used to specify any conditions on the newly defined

typetype The keyword The keyword condition condition is used to specify any is used to specify any

conditions on the newly defined typeconditions on the newly defined typeFor eg for RATIONAL ADTFor eg for RATIONAL ADTCondition Clause denominator may not be zeroCondition Clause denominator may not be zeroNote The definition clause is required but the Note The definition clause is required but the condition clause may not be necessary for every condition clause may not be necessary for every ADTADT

040823040823 1515

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator Definition It defines the operations that are to be It defines the operations that are to be

performed on a data setperformed on a data set Each operator is defined as an abstract Each operator is defined as an abstract

function with three partsfunction with three parts HeaderHeader Optional preconditions Optional preconditions Post conditions Post conditions

040823040823 1616

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator DefinitionFor eg Operator definition for RATIONAL ADTFor eg Operator definition for RATIONAL ADT includes the operations of creation addition includes the operations of creation addition multiplication and equalitymultiplication and equality Now for multiplication operation the operator definition for Now for multiplication operation the operator definition for

RATIONAL ADT isRATIONAL ADT is Abstract RATIONAL mult(ab)helliphellipAbstract RATIONAL mult(ab)helliphellipheaderheader

RATIONAL a b helliphelliphellip RATIONAL a b helliphelliphellip header headermul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip mul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip postcondpostcond

mul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellipmul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellippostcondpostcond

040823040823 1717

Complete example of RATIONL Complete example of RATIONL ADTADT

value definition value definition Abstract typedefAbstract typedeflt int int gtRATIONALlt int int gtRATIONAL ConditionCondition RATIONAL[1]=0 RATIONAL[1]=0 Operator definition Operator definition Abstract equal(ab)Abstract equal(ab) RATIONAL a bRATIONAL a b Postcondition equal==(a[0]b[1]==b[0]b[1])Postcondition equal==(a[0]b[1]==b[0]b[1]) Like this we can declare the other operationsLike this we can declare the other operations

040823040823 1818

Classification of Data StructureClassification of Data Structure

Linear and Non-LinearLinear and Non-Linear

In linear data structure the data items are arranged In linear data structure the data items are arranged in linear sequence eg Array Stack Queue Linked in linear sequence eg Array Stack Queue Linked ListList

In non-linear data items are not in sequence eg In non-linear data items are not in sequence eg Tree graph HeapTree graph Heap

040823040823 1919

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Homogenous and Non-homogenousHomogenous and Non-homogenous

In homogenous data structure all the elements are In homogenous data structure all the elements are of same type eg Arrayof same type eg Array

In non-homogenous data structure the elements In non-homogenous data structure the elements may or may not be of same type eg Recordmay or may not be of same type eg Record

040823040823 2020

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Primitive and Non-PrimitivePrimitive and Non-PrimitivePrimitive data structures constitute thePrimitive data structures constitute thenumber and the characters which are builtnumber and the characters which are builtprograms examples int realspointer programs examples int realspointer datacharaters data logical data datacharaters data logical data

040823040823 2121

What is STACK or Pushdown What is STACK or Pushdown ListList

A ordered collection of items A ordered collection of items into which new items may be into which new items may be inserted and from which items inserted and from which items may be deleted at one end may be deleted at one end called the top of stack called the top of stack

040823040823 2222

Operations on STACKOperations on STACK

PUSHWhen item is added in stackPUSHWhen item is added in stack POPWhen item is removed from POPWhen item is removed from

stackstack EMPTYStack containing no itemsEMPTYStack containing no items StackTopDetermine what the top StackTopDetermine what the top

item on a stack without removing item on a stack without removing itthis is a combination of push amp popitthis is a combination of push amp pop

040823040823 2323

Push amp Pop in STACKPush amp Pop in STACK PUSH OperationPUSH Operation PUSHPUSH(STACK TOPMAXITEM) (STACK TOPMAXITEM) STACK--STACK--Name given to ArrayName given to Array TOP----TOP----It contains the location of top It contains the location of top

elementselements MAX---MAX---It is maximum size of STACKIt is maximum size of STACK ITEM---gtValue that is to be store in stack ITEM---gtValue that is to be store in stack

ifif top = MAX top = MAX thenthen stackfull stackfull top = top+1 top = top+1 stack(top) = item stack(top) = item ReturnReturn

040823040823 2424

Push amp Pop in STACKPush amp Pop in STACK

POP OperationPOP Operation

POPPOP(STACK TOPITEM) (STACK TOPITEM)

ifif top = 0 top = 0 thenthen Underflow Underflow item = stack(top) item = stack(top) top = top-1 top = top-1 Return Return

040823040823 2525

Applications of STACKApplications of STACK

Expression EvaluationExpression EvaluationParenthesis CheckerParenthesis CheckerRecursionRecursion

040823040823 2626

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

Operator preecedenceOperator preecedence^ ---------Higher precedence^ ---------Higher precedence--------Next Precedence--------Next Precedence+_-------Least precedence+_-------Least precedence

040823040823 2727

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

The rules to rememberThe rules to remember

11 Parenthesize the expression Parenthesize the expression starting fro left to rightstarting fro left to right

22 During Parenthesizing the During Parenthesizing the

expression the operands associatedexpression the operands associated

with operator having higher with operator having higher

precedence are first parenthesizedprecedence are first parenthesized

040823040823 2828

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

33 The sub-expression which has been The sub-expression which has been converted into postfix is to be converted into postfix is to be treated as single operandtreated as single operand

44 Once the expression is converted to Once the expression is converted to postfix form remove the postfix form remove the parenthesis parenthesis

Example A+BCExample A+BC A+[(B+C)+(D+E)F]GA+[(B+C)+(D+E)F]G Answer ABC+DE+F+G+Answer ABC+DE+F+G+

040823040823 2929

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

Postfix(QP)Postfix(QP) QmdashgtGiven Infix expressionQmdashgtGiven Infix expression P-gtEquivalent Postfix expressionP-gtEquivalent Postfix expression

11 Push ldquo(ldquo onto STACK and add ldquo)rdquo to the Push ldquo(ldquo onto STACK and add ldquo)rdquo to the end of Qend of Q

22 Scan Q from left to right and repeat step 3 Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK to 6 for each element of Q until the STACK is Emptyis Empty

33 If an operand is encountered add it to PIf an operand is encountered add it to P44 If a left parenthesis is encountered push If a left parenthesis is encountered push

it onto STACK it onto STACK

040823040823 3030

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

55 If an operator reg is encountered If an operator reg is encountered thenthen

(a) ADD reg to STACK(a) ADD reg to STACK

[End of IF][End of IF]

(b) Repeatedly pop from STACK and (b) Repeatedly pop from STACK and add P each operator which has add P each operator which has same precedence as or higher same precedence as or higher precedence than regprecedence than reg

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 3: Data structure

040823040823 33

Computer Science amp Data Structure Computer Science amp Data Structure (Continue)(Continue)

33 Implementing the solutionImplementing the solution with a computer with a computer program This solution typically consists of program This solution typically consists of two parts two parts algorithms and data structuresalgorithms and data structures

AlgorithmAlgorithmAn algorithm is a concise specification of a methodAn algorithm is a concise specification of a method for solving a problemfor solving a problemData StructureData StructureA data structure can be viewed as consisting of a set A data structure can be viewed as consisting of a set of algorithms for performing operations on the dataof algorithms for performing operations on the data it stores it stores

040823040823 44

Computer Science amp Data Structure Computer Science amp Data Structure (Continue)(Continue)

Data Structure amp AlgorithmData Structure amp Algorithm

Algorithms are part of what constitutesAlgorithms are part of what constitutes

a data structure In constructing a solution toa data structure In constructing a solution to

a problem a data structure must be chosen a problem a data structure must be chosen

that allows the data to be operated upon that allows the data to be operated upon

easily in the manner required by the easily in the manner required by the

algorithmalgorithm

040823040823 55

12 Data Structures vs Algorithms

bullChoice of data structures 1048708A primary design consideration at many times 1048708Determines the algorithms to be used 1048708ldquoA well-designed data structure allows a variety of critical operations to be

performed using as few resources both execution time and memory space as possiblerdquo

bullThe opposite direction sometimes 1048708Certain algorithms require particular data structures 1048708Eg shortest path algorithm needs priority queues

ndash Data Structuresndash How do we organize ndash the data to be ndash handled

Algorithms Describe the process by which data is handledDuality

040823040823 66

040823040823 77

Abstract Data Types(ADT)Abstract Data Types(ADT)

What is AbstractionWhat is AbstractionTo abstract is to ignore some detailsTo abstract is to ignore some detailsof a thing in favor of othersof a thing in favor of others

ADT amp Data structureADT amp Data structureAn An Abstract Data TypeAbstract Data Type (ADT) is more a way of (ADT) is more a way of

looking at a data structure focusing on what it looking at a data structure focusing on what it does and ignoring how it does its job does and ignoring how it does its job

040823040823 88

Abstract Data Types(ADT)Abstract Data Types(ADT)

Why need AbstractionWhy need AbstractionAbstraction is important in problem solving because Abstraction is important in problem solving because it allows problem solvers to focus on essential details it allows problem solvers to focus on essential details while ignoring the inessential thus simplifying the while ignoring the inessential thus simplifying the problem and bringing to attention those aspects of the problem and bringing to attention those aspects of the problem involved in its solution Once an abstract problem involved in its solution Once an abstract data type is understood and documented it serves as a data type is understood and documented it serves as a specification that programmers can use to guide their specification that programmers can use to guide their choice of data representation and operation choice of data representation and operation implementation and as a standard for ensuring implementation and as a standard for ensuring program correctness program correctness

040823040823 99

Abstract Data Types(ADT)Abstract Data Types(ADT)Abstract data typesAbstract data typesEach data structure can be developed around the Each data structure can be developed around the concept of an abstract data type that defines both dataconcept of an abstract data type that defines both dataorganization and data handling operationsorganization and data handling operations A mathematical entity consisting of a set of values A mathematical entity consisting of a set of values

and a collection of operations that manipulate them and a collection of operations that manipulate them For example the Integer abstract data type consists of For example the Integer abstract data type consists of a carrier set containing the positive and negative a carrier set containing the positive and negative whole numbers and 0 and a collection of operations whole numbers and 0 and a collection of operations manipulating these values such as addition manipulating these values such as addition subtraction multiplication equality comparison and subtraction multiplication equality comparison and order comparisonorder comparison

040823040823 1010

Abstract Data Types(ADT)Abstract Data Types(ADT) Abstract data types are important in computer science Abstract data types are important in computer science

because they provide a clear and precise way to because they provide a clear and precise way to specify what data a program must manipulate and specify what data a program must manipulate and how the program must manipulate its data without how the program must manipulate its data without regard to details about how data are represented or regard to details about how data are represented or how operations are implementedhow operations are implemented

ADT defines both data organization and data ADT defines both data organization and data handling operations handling operations

The study of data structure is organized around a The study of data structure is organized around a collection of abstract data types that includes lists collection of abstract data types that includes lists trees sets graphs and dictionaries trees sets graphs and dictionaries

040823040823 1111

Abstract Data Types(ADT)Abstract Data Types(ADT)

ADT is not a part of a program since a ADT is not a part of a program since a program written in a programming language program written in a programming language requires the definition of data structure not requires the definition of data structure not just the operations on the data structurejust the operations on the data structure

ADT is a useful tool for specifying the logical ADT is a useful tool for specifying the logical properties of a data typeproperties of a data type

ADT is not concerned with the timespace ADT is not concerned with the timespace efficiency of data typeefficiency of data type

040823040823 1212

Specification of ADTSpecification of ADT

ADT consist of 2 partsADT consist of 2 parts11 Value DefinitionValue Definition

22 Operator DefinitionOperator Definition

040823040823 1313

Specification of ADTSpecification of ADT

11 Value DefinitionValue DefinitionIt defines the collection of values for the It defines the collection of values for the ADT and consist of two partsADT and consist of two partsa)a) Definition Clause Definition Clause b)b) Condition ClauseCondition Clause eg For ADT RATIONAL eg For ADT RATIONAL Value definition it states that RATIONAL value Value definition it states that RATIONAL value consist of two integers the second of which does not equal consist of two integers the second of which does not equal to zeroto zeroThe keyword The keyword abstract typedefabstract typedef introduce a value definition introduce a value definition

040823040823 1414

Specification of ADTSpecification of ADT

Condition ClauseCondition Clause Used to specify any conditions on the newly defined Used to specify any conditions on the newly defined

typetype The keyword The keyword condition condition is used to specify any is used to specify any

conditions on the newly defined typeconditions on the newly defined typeFor eg for RATIONAL ADTFor eg for RATIONAL ADTCondition Clause denominator may not be zeroCondition Clause denominator may not be zeroNote The definition clause is required but the Note The definition clause is required but the condition clause may not be necessary for every condition clause may not be necessary for every ADTADT

040823040823 1515

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator Definition It defines the operations that are to be It defines the operations that are to be

performed on a data setperformed on a data set Each operator is defined as an abstract Each operator is defined as an abstract

function with three partsfunction with three parts HeaderHeader Optional preconditions Optional preconditions Post conditions Post conditions

040823040823 1616

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator DefinitionFor eg Operator definition for RATIONAL ADTFor eg Operator definition for RATIONAL ADT includes the operations of creation addition includes the operations of creation addition multiplication and equalitymultiplication and equality Now for multiplication operation the operator definition for Now for multiplication operation the operator definition for

RATIONAL ADT isRATIONAL ADT is Abstract RATIONAL mult(ab)helliphellipAbstract RATIONAL mult(ab)helliphellipheaderheader

RATIONAL a b helliphelliphellip RATIONAL a b helliphelliphellip header headermul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip mul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip postcondpostcond

mul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellipmul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellippostcondpostcond

040823040823 1717

Complete example of RATIONL Complete example of RATIONL ADTADT

value definition value definition Abstract typedefAbstract typedeflt int int gtRATIONALlt int int gtRATIONAL ConditionCondition RATIONAL[1]=0 RATIONAL[1]=0 Operator definition Operator definition Abstract equal(ab)Abstract equal(ab) RATIONAL a bRATIONAL a b Postcondition equal==(a[0]b[1]==b[0]b[1])Postcondition equal==(a[0]b[1]==b[0]b[1]) Like this we can declare the other operationsLike this we can declare the other operations

040823040823 1818

Classification of Data StructureClassification of Data Structure

Linear and Non-LinearLinear and Non-Linear

In linear data structure the data items are arranged In linear data structure the data items are arranged in linear sequence eg Array Stack Queue Linked in linear sequence eg Array Stack Queue Linked ListList

In non-linear data items are not in sequence eg In non-linear data items are not in sequence eg Tree graph HeapTree graph Heap

040823040823 1919

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Homogenous and Non-homogenousHomogenous and Non-homogenous

In homogenous data structure all the elements are In homogenous data structure all the elements are of same type eg Arrayof same type eg Array

In non-homogenous data structure the elements In non-homogenous data structure the elements may or may not be of same type eg Recordmay or may not be of same type eg Record

040823040823 2020

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Primitive and Non-PrimitivePrimitive and Non-PrimitivePrimitive data structures constitute thePrimitive data structures constitute thenumber and the characters which are builtnumber and the characters which are builtprograms examples int realspointer programs examples int realspointer datacharaters data logical data datacharaters data logical data

040823040823 2121

What is STACK or Pushdown What is STACK or Pushdown ListList

A ordered collection of items A ordered collection of items into which new items may be into which new items may be inserted and from which items inserted and from which items may be deleted at one end may be deleted at one end called the top of stack called the top of stack

040823040823 2222

Operations on STACKOperations on STACK

PUSHWhen item is added in stackPUSHWhen item is added in stack POPWhen item is removed from POPWhen item is removed from

stackstack EMPTYStack containing no itemsEMPTYStack containing no items StackTopDetermine what the top StackTopDetermine what the top

item on a stack without removing item on a stack without removing itthis is a combination of push amp popitthis is a combination of push amp pop

040823040823 2323

Push amp Pop in STACKPush amp Pop in STACK PUSH OperationPUSH Operation PUSHPUSH(STACK TOPMAXITEM) (STACK TOPMAXITEM) STACK--STACK--Name given to ArrayName given to Array TOP----TOP----It contains the location of top It contains the location of top

elementselements MAX---MAX---It is maximum size of STACKIt is maximum size of STACK ITEM---gtValue that is to be store in stack ITEM---gtValue that is to be store in stack

ifif top = MAX top = MAX thenthen stackfull stackfull top = top+1 top = top+1 stack(top) = item stack(top) = item ReturnReturn

040823040823 2424

Push amp Pop in STACKPush amp Pop in STACK

POP OperationPOP Operation

POPPOP(STACK TOPITEM) (STACK TOPITEM)

ifif top = 0 top = 0 thenthen Underflow Underflow item = stack(top) item = stack(top) top = top-1 top = top-1 Return Return

040823040823 2525

Applications of STACKApplications of STACK

Expression EvaluationExpression EvaluationParenthesis CheckerParenthesis CheckerRecursionRecursion

040823040823 2626

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

Operator preecedenceOperator preecedence^ ---------Higher precedence^ ---------Higher precedence--------Next Precedence--------Next Precedence+_-------Least precedence+_-------Least precedence

040823040823 2727

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

The rules to rememberThe rules to remember

11 Parenthesize the expression Parenthesize the expression starting fro left to rightstarting fro left to right

22 During Parenthesizing the During Parenthesizing the

expression the operands associatedexpression the operands associated

with operator having higher with operator having higher

precedence are first parenthesizedprecedence are first parenthesized

040823040823 2828

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

33 The sub-expression which has been The sub-expression which has been converted into postfix is to be converted into postfix is to be treated as single operandtreated as single operand

44 Once the expression is converted to Once the expression is converted to postfix form remove the postfix form remove the parenthesis parenthesis

Example A+BCExample A+BC A+[(B+C)+(D+E)F]GA+[(B+C)+(D+E)F]G Answer ABC+DE+F+G+Answer ABC+DE+F+G+

040823040823 2929

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

Postfix(QP)Postfix(QP) QmdashgtGiven Infix expressionQmdashgtGiven Infix expression P-gtEquivalent Postfix expressionP-gtEquivalent Postfix expression

11 Push ldquo(ldquo onto STACK and add ldquo)rdquo to the Push ldquo(ldquo onto STACK and add ldquo)rdquo to the end of Qend of Q

22 Scan Q from left to right and repeat step 3 Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK to 6 for each element of Q until the STACK is Emptyis Empty

33 If an operand is encountered add it to PIf an operand is encountered add it to P44 If a left parenthesis is encountered push If a left parenthesis is encountered push

it onto STACK it onto STACK

040823040823 3030

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

55 If an operator reg is encountered If an operator reg is encountered thenthen

(a) ADD reg to STACK(a) ADD reg to STACK

[End of IF][End of IF]

(b) Repeatedly pop from STACK and (b) Repeatedly pop from STACK and add P each operator which has add P each operator which has same precedence as or higher same precedence as or higher precedence than regprecedence than reg

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 4: Data structure

040823040823 44

Computer Science amp Data Structure Computer Science amp Data Structure (Continue)(Continue)

Data Structure amp AlgorithmData Structure amp Algorithm

Algorithms are part of what constitutesAlgorithms are part of what constitutes

a data structure In constructing a solution toa data structure In constructing a solution to

a problem a data structure must be chosen a problem a data structure must be chosen

that allows the data to be operated upon that allows the data to be operated upon

easily in the manner required by the easily in the manner required by the

algorithmalgorithm

040823040823 55

12 Data Structures vs Algorithms

bullChoice of data structures 1048708A primary design consideration at many times 1048708Determines the algorithms to be used 1048708ldquoA well-designed data structure allows a variety of critical operations to be

performed using as few resources both execution time and memory space as possiblerdquo

bullThe opposite direction sometimes 1048708Certain algorithms require particular data structures 1048708Eg shortest path algorithm needs priority queues

ndash Data Structuresndash How do we organize ndash the data to be ndash handled

Algorithms Describe the process by which data is handledDuality

040823040823 66

040823040823 77

Abstract Data Types(ADT)Abstract Data Types(ADT)

What is AbstractionWhat is AbstractionTo abstract is to ignore some detailsTo abstract is to ignore some detailsof a thing in favor of othersof a thing in favor of others

ADT amp Data structureADT amp Data structureAn An Abstract Data TypeAbstract Data Type (ADT) is more a way of (ADT) is more a way of

looking at a data structure focusing on what it looking at a data structure focusing on what it does and ignoring how it does its job does and ignoring how it does its job

040823040823 88

Abstract Data Types(ADT)Abstract Data Types(ADT)

Why need AbstractionWhy need AbstractionAbstraction is important in problem solving because Abstraction is important in problem solving because it allows problem solvers to focus on essential details it allows problem solvers to focus on essential details while ignoring the inessential thus simplifying the while ignoring the inessential thus simplifying the problem and bringing to attention those aspects of the problem and bringing to attention those aspects of the problem involved in its solution Once an abstract problem involved in its solution Once an abstract data type is understood and documented it serves as a data type is understood and documented it serves as a specification that programmers can use to guide their specification that programmers can use to guide their choice of data representation and operation choice of data representation and operation implementation and as a standard for ensuring implementation and as a standard for ensuring program correctness program correctness

040823040823 99

Abstract Data Types(ADT)Abstract Data Types(ADT)Abstract data typesAbstract data typesEach data structure can be developed around the Each data structure can be developed around the concept of an abstract data type that defines both dataconcept of an abstract data type that defines both dataorganization and data handling operationsorganization and data handling operations A mathematical entity consisting of a set of values A mathematical entity consisting of a set of values

and a collection of operations that manipulate them and a collection of operations that manipulate them For example the Integer abstract data type consists of For example the Integer abstract data type consists of a carrier set containing the positive and negative a carrier set containing the positive and negative whole numbers and 0 and a collection of operations whole numbers and 0 and a collection of operations manipulating these values such as addition manipulating these values such as addition subtraction multiplication equality comparison and subtraction multiplication equality comparison and order comparisonorder comparison

040823040823 1010

Abstract Data Types(ADT)Abstract Data Types(ADT) Abstract data types are important in computer science Abstract data types are important in computer science

because they provide a clear and precise way to because they provide a clear and precise way to specify what data a program must manipulate and specify what data a program must manipulate and how the program must manipulate its data without how the program must manipulate its data without regard to details about how data are represented or regard to details about how data are represented or how operations are implementedhow operations are implemented

ADT defines both data organization and data ADT defines both data organization and data handling operations handling operations

The study of data structure is organized around a The study of data structure is organized around a collection of abstract data types that includes lists collection of abstract data types that includes lists trees sets graphs and dictionaries trees sets graphs and dictionaries

040823040823 1111

Abstract Data Types(ADT)Abstract Data Types(ADT)

ADT is not a part of a program since a ADT is not a part of a program since a program written in a programming language program written in a programming language requires the definition of data structure not requires the definition of data structure not just the operations on the data structurejust the operations on the data structure

ADT is a useful tool for specifying the logical ADT is a useful tool for specifying the logical properties of a data typeproperties of a data type

ADT is not concerned with the timespace ADT is not concerned with the timespace efficiency of data typeefficiency of data type

040823040823 1212

Specification of ADTSpecification of ADT

ADT consist of 2 partsADT consist of 2 parts11 Value DefinitionValue Definition

22 Operator DefinitionOperator Definition

040823040823 1313

Specification of ADTSpecification of ADT

11 Value DefinitionValue DefinitionIt defines the collection of values for the It defines the collection of values for the ADT and consist of two partsADT and consist of two partsa)a) Definition Clause Definition Clause b)b) Condition ClauseCondition Clause eg For ADT RATIONAL eg For ADT RATIONAL Value definition it states that RATIONAL value Value definition it states that RATIONAL value consist of two integers the second of which does not equal consist of two integers the second of which does not equal to zeroto zeroThe keyword The keyword abstract typedefabstract typedef introduce a value definition introduce a value definition

040823040823 1414

Specification of ADTSpecification of ADT

Condition ClauseCondition Clause Used to specify any conditions on the newly defined Used to specify any conditions on the newly defined

typetype The keyword The keyword condition condition is used to specify any is used to specify any

conditions on the newly defined typeconditions on the newly defined typeFor eg for RATIONAL ADTFor eg for RATIONAL ADTCondition Clause denominator may not be zeroCondition Clause denominator may not be zeroNote The definition clause is required but the Note The definition clause is required but the condition clause may not be necessary for every condition clause may not be necessary for every ADTADT

040823040823 1515

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator Definition It defines the operations that are to be It defines the operations that are to be

performed on a data setperformed on a data set Each operator is defined as an abstract Each operator is defined as an abstract

function with three partsfunction with three parts HeaderHeader Optional preconditions Optional preconditions Post conditions Post conditions

040823040823 1616

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator DefinitionFor eg Operator definition for RATIONAL ADTFor eg Operator definition for RATIONAL ADT includes the operations of creation addition includes the operations of creation addition multiplication and equalitymultiplication and equality Now for multiplication operation the operator definition for Now for multiplication operation the operator definition for

RATIONAL ADT isRATIONAL ADT is Abstract RATIONAL mult(ab)helliphellipAbstract RATIONAL mult(ab)helliphellipheaderheader

RATIONAL a b helliphelliphellip RATIONAL a b helliphelliphellip header headermul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip mul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip postcondpostcond

mul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellipmul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellippostcondpostcond

040823040823 1717

Complete example of RATIONL Complete example of RATIONL ADTADT

value definition value definition Abstract typedefAbstract typedeflt int int gtRATIONALlt int int gtRATIONAL ConditionCondition RATIONAL[1]=0 RATIONAL[1]=0 Operator definition Operator definition Abstract equal(ab)Abstract equal(ab) RATIONAL a bRATIONAL a b Postcondition equal==(a[0]b[1]==b[0]b[1])Postcondition equal==(a[0]b[1]==b[0]b[1]) Like this we can declare the other operationsLike this we can declare the other operations

040823040823 1818

Classification of Data StructureClassification of Data Structure

Linear and Non-LinearLinear and Non-Linear

In linear data structure the data items are arranged In linear data structure the data items are arranged in linear sequence eg Array Stack Queue Linked in linear sequence eg Array Stack Queue Linked ListList

In non-linear data items are not in sequence eg In non-linear data items are not in sequence eg Tree graph HeapTree graph Heap

040823040823 1919

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Homogenous and Non-homogenousHomogenous and Non-homogenous

In homogenous data structure all the elements are In homogenous data structure all the elements are of same type eg Arrayof same type eg Array

In non-homogenous data structure the elements In non-homogenous data structure the elements may or may not be of same type eg Recordmay or may not be of same type eg Record

040823040823 2020

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Primitive and Non-PrimitivePrimitive and Non-PrimitivePrimitive data structures constitute thePrimitive data structures constitute thenumber and the characters which are builtnumber and the characters which are builtprograms examples int realspointer programs examples int realspointer datacharaters data logical data datacharaters data logical data

040823040823 2121

What is STACK or Pushdown What is STACK or Pushdown ListList

A ordered collection of items A ordered collection of items into which new items may be into which new items may be inserted and from which items inserted and from which items may be deleted at one end may be deleted at one end called the top of stack called the top of stack

040823040823 2222

Operations on STACKOperations on STACK

PUSHWhen item is added in stackPUSHWhen item is added in stack POPWhen item is removed from POPWhen item is removed from

stackstack EMPTYStack containing no itemsEMPTYStack containing no items StackTopDetermine what the top StackTopDetermine what the top

item on a stack without removing item on a stack without removing itthis is a combination of push amp popitthis is a combination of push amp pop

040823040823 2323

Push amp Pop in STACKPush amp Pop in STACK PUSH OperationPUSH Operation PUSHPUSH(STACK TOPMAXITEM) (STACK TOPMAXITEM) STACK--STACK--Name given to ArrayName given to Array TOP----TOP----It contains the location of top It contains the location of top

elementselements MAX---MAX---It is maximum size of STACKIt is maximum size of STACK ITEM---gtValue that is to be store in stack ITEM---gtValue that is to be store in stack

ifif top = MAX top = MAX thenthen stackfull stackfull top = top+1 top = top+1 stack(top) = item stack(top) = item ReturnReturn

040823040823 2424

Push amp Pop in STACKPush amp Pop in STACK

POP OperationPOP Operation

POPPOP(STACK TOPITEM) (STACK TOPITEM)

ifif top = 0 top = 0 thenthen Underflow Underflow item = stack(top) item = stack(top) top = top-1 top = top-1 Return Return

040823040823 2525

Applications of STACKApplications of STACK

Expression EvaluationExpression EvaluationParenthesis CheckerParenthesis CheckerRecursionRecursion

040823040823 2626

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

Operator preecedenceOperator preecedence^ ---------Higher precedence^ ---------Higher precedence--------Next Precedence--------Next Precedence+_-------Least precedence+_-------Least precedence

040823040823 2727

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

The rules to rememberThe rules to remember

11 Parenthesize the expression Parenthesize the expression starting fro left to rightstarting fro left to right

22 During Parenthesizing the During Parenthesizing the

expression the operands associatedexpression the operands associated

with operator having higher with operator having higher

precedence are first parenthesizedprecedence are first parenthesized

040823040823 2828

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

33 The sub-expression which has been The sub-expression which has been converted into postfix is to be converted into postfix is to be treated as single operandtreated as single operand

44 Once the expression is converted to Once the expression is converted to postfix form remove the postfix form remove the parenthesis parenthesis

Example A+BCExample A+BC A+[(B+C)+(D+E)F]GA+[(B+C)+(D+E)F]G Answer ABC+DE+F+G+Answer ABC+DE+F+G+

040823040823 2929

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

Postfix(QP)Postfix(QP) QmdashgtGiven Infix expressionQmdashgtGiven Infix expression P-gtEquivalent Postfix expressionP-gtEquivalent Postfix expression

11 Push ldquo(ldquo onto STACK and add ldquo)rdquo to the Push ldquo(ldquo onto STACK and add ldquo)rdquo to the end of Qend of Q

22 Scan Q from left to right and repeat step 3 Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK to 6 for each element of Q until the STACK is Emptyis Empty

33 If an operand is encountered add it to PIf an operand is encountered add it to P44 If a left parenthesis is encountered push If a left parenthesis is encountered push

it onto STACK it onto STACK

040823040823 3030

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

55 If an operator reg is encountered If an operator reg is encountered thenthen

(a) ADD reg to STACK(a) ADD reg to STACK

[End of IF][End of IF]

(b) Repeatedly pop from STACK and (b) Repeatedly pop from STACK and add P each operator which has add P each operator which has same precedence as or higher same precedence as or higher precedence than regprecedence than reg

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 5: Data structure

040823040823 55

12 Data Structures vs Algorithms

bullChoice of data structures 1048708A primary design consideration at many times 1048708Determines the algorithms to be used 1048708ldquoA well-designed data structure allows a variety of critical operations to be

performed using as few resources both execution time and memory space as possiblerdquo

bullThe opposite direction sometimes 1048708Certain algorithms require particular data structures 1048708Eg shortest path algorithm needs priority queues

ndash Data Structuresndash How do we organize ndash the data to be ndash handled

Algorithms Describe the process by which data is handledDuality

040823040823 66

040823040823 77

Abstract Data Types(ADT)Abstract Data Types(ADT)

What is AbstractionWhat is AbstractionTo abstract is to ignore some detailsTo abstract is to ignore some detailsof a thing in favor of othersof a thing in favor of others

ADT amp Data structureADT amp Data structureAn An Abstract Data TypeAbstract Data Type (ADT) is more a way of (ADT) is more a way of

looking at a data structure focusing on what it looking at a data structure focusing on what it does and ignoring how it does its job does and ignoring how it does its job

040823040823 88

Abstract Data Types(ADT)Abstract Data Types(ADT)

Why need AbstractionWhy need AbstractionAbstraction is important in problem solving because Abstraction is important in problem solving because it allows problem solvers to focus on essential details it allows problem solvers to focus on essential details while ignoring the inessential thus simplifying the while ignoring the inessential thus simplifying the problem and bringing to attention those aspects of the problem and bringing to attention those aspects of the problem involved in its solution Once an abstract problem involved in its solution Once an abstract data type is understood and documented it serves as a data type is understood and documented it serves as a specification that programmers can use to guide their specification that programmers can use to guide their choice of data representation and operation choice of data representation and operation implementation and as a standard for ensuring implementation and as a standard for ensuring program correctness program correctness

040823040823 99

Abstract Data Types(ADT)Abstract Data Types(ADT)Abstract data typesAbstract data typesEach data structure can be developed around the Each data structure can be developed around the concept of an abstract data type that defines both dataconcept of an abstract data type that defines both dataorganization and data handling operationsorganization and data handling operations A mathematical entity consisting of a set of values A mathematical entity consisting of a set of values

and a collection of operations that manipulate them and a collection of operations that manipulate them For example the Integer abstract data type consists of For example the Integer abstract data type consists of a carrier set containing the positive and negative a carrier set containing the positive and negative whole numbers and 0 and a collection of operations whole numbers and 0 and a collection of operations manipulating these values such as addition manipulating these values such as addition subtraction multiplication equality comparison and subtraction multiplication equality comparison and order comparisonorder comparison

040823040823 1010

Abstract Data Types(ADT)Abstract Data Types(ADT) Abstract data types are important in computer science Abstract data types are important in computer science

because they provide a clear and precise way to because they provide a clear and precise way to specify what data a program must manipulate and specify what data a program must manipulate and how the program must manipulate its data without how the program must manipulate its data without regard to details about how data are represented or regard to details about how data are represented or how operations are implementedhow operations are implemented

ADT defines both data organization and data ADT defines both data organization and data handling operations handling operations

The study of data structure is organized around a The study of data structure is organized around a collection of abstract data types that includes lists collection of abstract data types that includes lists trees sets graphs and dictionaries trees sets graphs and dictionaries

040823040823 1111

Abstract Data Types(ADT)Abstract Data Types(ADT)

ADT is not a part of a program since a ADT is not a part of a program since a program written in a programming language program written in a programming language requires the definition of data structure not requires the definition of data structure not just the operations on the data structurejust the operations on the data structure

ADT is a useful tool for specifying the logical ADT is a useful tool for specifying the logical properties of a data typeproperties of a data type

ADT is not concerned with the timespace ADT is not concerned with the timespace efficiency of data typeefficiency of data type

040823040823 1212

Specification of ADTSpecification of ADT

ADT consist of 2 partsADT consist of 2 parts11 Value DefinitionValue Definition

22 Operator DefinitionOperator Definition

040823040823 1313

Specification of ADTSpecification of ADT

11 Value DefinitionValue DefinitionIt defines the collection of values for the It defines the collection of values for the ADT and consist of two partsADT and consist of two partsa)a) Definition Clause Definition Clause b)b) Condition ClauseCondition Clause eg For ADT RATIONAL eg For ADT RATIONAL Value definition it states that RATIONAL value Value definition it states that RATIONAL value consist of two integers the second of which does not equal consist of two integers the second of which does not equal to zeroto zeroThe keyword The keyword abstract typedefabstract typedef introduce a value definition introduce a value definition

040823040823 1414

Specification of ADTSpecification of ADT

Condition ClauseCondition Clause Used to specify any conditions on the newly defined Used to specify any conditions on the newly defined

typetype The keyword The keyword condition condition is used to specify any is used to specify any

conditions on the newly defined typeconditions on the newly defined typeFor eg for RATIONAL ADTFor eg for RATIONAL ADTCondition Clause denominator may not be zeroCondition Clause denominator may not be zeroNote The definition clause is required but the Note The definition clause is required but the condition clause may not be necessary for every condition clause may not be necessary for every ADTADT

040823040823 1515

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator Definition It defines the operations that are to be It defines the operations that are to be

performed on a data setperformed on a data set Each operator is defined as an abstract Each operator is defined as an abstract

function with three partsfunction with three parts HeaderHeader Optional preconditions Optional preconditions Post conditions Post conditions

040823040823 1616

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator DefinitionFor eg Operator definition for RATIONAL ADTFor eg Operator definition for RATIONAL ADT includes the operations of creation addition includes the operations of creation addition multiplication and equalitymultiplication and equality Now for multiplication operation the operator definition for Now for multiplication operation the operator definition for

RATIONAL ADT isRATIONAL ADT is Abstract RATIONAL mult(ab)helliphellipAbstract RATIONAL mult(ab)helliphellipheaderheader

RATIONAL a b helliphelliphellip RATIONAL a b helliphelliphellip header headermul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip mul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip postcondpostcond

mul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellipmul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellippostcondpostcond

040823040823 1717

Complete example of RATIONL Complete example of RATIONL ADTADT

value definition value definition Abstract typedefAbstract typedeflt int int gtRATIONALlt int int gtRATIONAL ConditionCondition RATIONAL[1]=0 RATIONAL[1]=0 Operator definition Operator definition Abstract equal(ab)Abstract equal(ab) RATIONAL a bRATIONAL a b Postcondition equal==(a[0]b[1]==b[0]b[1])Postcondition equal==(a[0]b[1]==b[0]b[1]) Like this we can declare the other operationsLike this we can declare the other operations

040823040823 1818

Classification of Data StructureClassification of Data Structure

Linear and Non-LinearLinear and Non-Linear

In linear data structure the data items are arranged In linear data structure the data items are arranged in linear sequence eg Array Stack Queue Linked in linear sequence eg Array Stack Queue Linked ListList

In non-linear data items are not in sequence eg In non-linear data items are not in sequence eg Tree graph HeapTree graph Heap

040823040823 1919

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Homogenous and Non-homogenousHomogenous and Non-homogenous

In homogenous data structure all the elements are In homogenous data structure all the elements are of same type eg Arrayof same type eg Array

In non-homogenous data structure the elements In non-homogenous data structure the elements may or may not be of same type eg Recordmay or may not be of same type eg Record

040823040823 2020

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Primitive and Non-PrimitivePrimitive and Non-PrimitivePrimitive data structures constitute thePrimitive data structures constitute thenumber and the characters which are builtnumber and the characters which are builtprograms examples int realspointer programs examples int realspointer datacharaters data logical data datacharaters data logical data

040823040823 2121

What is STACK or Pushdown What is STACK or Pushdown ListList

A ordered collection of items A ordered collection of items into which new items may be into which new items may be inserted and from which items inserted and from which items may be deleted at one end may be deleted at one end called the top of stack called the top of stack

040823040823 2222

Operations on STACKOperations on STACK

PUSHWhen item is added in stackPUSHWhen item is added in stack POPWhen item is removed from POPWhen item is removed from

stackstack EMPTYStack containing no itemsEMPTYStack containing no items StackTopDetermine what the top StackTopDetermine what the top

item on a stack without removing item on a stack without removing itthis is a combination of push amp popitthis is a combination of push amp pop

040823040823 2323

Push amp Pop in STACKPush amp Pop in STACK PUSH OperationPUSH Operation PUSHPUSH(STACK TOPMAXITEM) (STACK TOPMAXITEM) STACK--STACK--Name given to ArrayName given to Array TOP----TOP----It contains the location of top It contains the location of top

elementselements MAX---MAX---It is maximum size of STACKIt is maximum size of STACK ITEM---gtValue that is to be store in stack ITEM---gtValue that is to be store in stack

ifif top = MAX top = MAX thenthen stackfull stackfull top = top+1 top = top+1 stack(top) = item stack(top) = item ReturnReturn

040823040823 2424

Push amp Pop in STACKPush amp Pop in STACK

POP OperationPOP Operation

POPPOP(STACK TOPITEM) (STACK TOPITEM)

ifif top = 0 top = 0 thenthen Underflow Underflow item = stack(top) item = stack(top) top = top-1 top = top-1 Return Return

040823040823 2525

Applications of STACKApplications of STACK

Expression EvaluationExpression EvaluationParenthesis CheckerParenthesis CheckerRecursionRecursion

040823040823 2626

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

Operator preecedenceOperator preecedence^ ---------Higher precedence^ ---------Higher precedence--------Next Precedence--------Next Precedence+_-------Least precedence+_-------Least precedence

040823040823 2727

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

The rules to rememberThe rules to remember

11 Parenthesize the expression Parenthesize the expression starting fro left to rightstarting fro left to right

22 During Parenthesizing the During Parenthesizing the

expression the operands associatedexpression the operands associated

with operator having higher with operator having higher

precedence are first parenthesizedprecedence are first parenthesized

040823040823 2828

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

33 The sub-expression which has been The sub-expression which has been converted into postfix is to be converted into postfix is to be treated as single operandtreated as single operand

44 Once the expression is converted to Once the expression is converted to postfix form remove the postfix form remove the parenthesis parenthesis

Example A+BCExample A+BC A+[(B+C)+(D+E)F]GA+[(B+C)+(D+E)F]G Answer ABC+DE+F+G+Answer ABC+DE+F+G+

040823040823 2929

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

Postfix(QP)Postfix(QP) QmdashgtGiven Infix expressionQmdashgtGiven Infix expression P-gtEquivalent Postfix expressionP-gtEquivalent Postfix expression

11 Push ldquo(ldquo onto STACK and add ldquo)rdquo to the Push ldquo(ldquo onto STACK and add ldquo)rdquo to the end of Qend of Q

22 Scan Q from left to right and repeat step 3 Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK to 6 for each element of Q until the STACK is Emptyis Empty

33 If an operand is encountered add it to PIf an operand is encountered add it to P44 If a left parenthesis is encountered push If a left parenthesis is encountered push

it onto STACK it onto STACK

040823040823 3030

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

55 If an operator reg is encountered If an operator reg is encountered thenthen

(a) ADD reg to STACK(a) ADD reg to STACK

[End of IF][End of IF]

(b) Repeatedly pop from STACK and (b) Repeatedly pop from STACK and add P each operator which has add P each operator which has same precedence as or higher same precedence as or higher precedence than regprecedence than reg

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 6: Data structure

040823040823 66

040823040823 77

Abstract Data Types(ADT)Abstract Data Types(ADT)

What is AbstractionWhat is AbstractionTo abstract is to ignore some detailsTo abstract is to ignore some detailsof a thing in favor of othersof a thing in favor of others

ADT amp Data structureADT amp Data structureAn An Abstract Data TypeAbstract Data Type (ADT) is more a way of (ADT) is more a way of

looking at a data structure focusing on what it looking at a data structure focusing on what it does and ignoring how it does its job does and ignoring how it does its job

040823040823 88

Abstract Data Types(ADT)Abstract Data Types(ADT)

Why need AbstractionWhy need AbstractionAbstraction is important in problem solving because Abstraction is important in problem solving because it allows problem solvers to focus on essential details it allows problem solvers to focus on essential details while ignoring the inessential thus simplifying the while ignoring the inessential thus simplifying the problem and bringing to attention those aspects of the problem and bringing to attention those aspects of the problem involved in its solution Once an abstract problem involved in its solution Once an abstract data type is understood and documented it serves as a data type is understood and documented it serves as a specification that programmers can use to guide their specification that programmers can use to guide their choice of data representation and operation choice of data representation and operation implementation and as a standard for ensuring implementation and as a standard for ensuring program correctness program correctness

040823040823 99

Abstract Data Types(ADT)Abstract Data Types(ADT)Abstract data typesAbstract data typesEach data structure can be developed around the Each data structure can be developed around the concept of an abstract data type that defines both dataconcept of an abstract data type that defines both dataorganization and data handling operationsorganization and data handling operations A mathematical entity consisting of a set of values A mathematical entity consisting of a set of values

and a collection of operations that manipulate them and a collection of operations that manipulate them For example the Integer abstract data type consists of For example the Integer abstract data type consists of a carrier set containing the positive and negative a carrier set containing the positive and negative whole numbers and 0 and a collection of operations whole numbers and 0 and a collection of operations manipulating these values such as addition manipulating these values such as addition subtraction multiplication equality comparison and subtraction multiplication equality comparison and order comparisonorder comparison

040823040823 1010

Abstract Data Types(ADT)Abstract Data Types(ADT) Abstract data types are important in computer science Abstract data types are important in computer science

because they provide a clear and precise way to because they provide a clear and precise way to specify what data a program must manipulate and specify what data a program must manipulate and how the program must manipulate its data without how the program must manipulate its data without regard to details about how data are represented or regard to details about how data are represented or how operations are implementedhow operations are implemented

ADT defines both data organization and data ADT defines both data organization and data handling operations handling operations

The study of data structure is organized around a The study of data structure is organized around a collection of abstract data types that includes lists collection of abstract data types that includes lists trees sets graphs and dictionaries trees sets graphs and dictionaries

040823040823 1111

Abstract Data Types(ADT)Abstract Data Types(ADT)

ADT is not a part of a program since a ADT is not a part of a program since a program written in a programming language program written in a programming language requires the definition of data structure not requires the definition of data structure not just the operations on the data structurejust the operations on the data structure

ADT is a useful tool for specifying the logical ADT is a useful tool for specifying the logical properties of a data typeproperties of a data type

ADT is not concerned with the timespace ADT is not concerned with the timespace efficiency of data typeefficiency of data type

040823040823 1212

Specification of ADTSpecification of ADT

ADT consist of 2 partsADT consist of 2 parts11 Value DefinitionValue Definition

22 Operator DefinitionOperator Definition

040823040823 1313

Specification of ADTSpecification of ADT

11 Value DefinitionValue DefinitionIt defines the collection of values for the It defines the collection of values for the ADT and consist of two partsADT and consist of two partsa)a) Definition Clause Definition Clause b)b) Condition ClauseCondition Clause eg For ADT RATIONAL eg For ADT RATIONAL Value definition it states that RATIONAL value Value definition it states that RATIONAL value consist of two integers the second of which does not equal consist of two integers the second of which does not equal to zeroto zeroThe keyword The keyword abstract typedefabstract typedef introduce a value definition introduce a value definition

040823040823 1414

Specification of ADTSpecification of ADT

Condition ClauseCondition Clause Used to specify any conditions on the newly defined Used to specify any conditions on the newly defined

typetype The keyword The keyword condition condition is used to specify any is used to specify any

conditions on the newly defined typeconditions on the newly defined typeFor eg for RATIONAL ADTFor eg for RATIONAL ADTCondition Clause denominator may not be zeroCondition Clause denominator may not be zeroNote The definition clause is required but the Note The definition clause is required but the condition clause may not be necessary for every condition clause may not be necessary for every ADTADT

040823040823 1515

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator Definition It defines the operations that are to be It defines the operations that are to be

performed on a data setperformed on a data set Each operator is defined as an abstract Each operator is defined as an abstract

function with three partsfunction with three parts HeaderHeader Optional preconditions Optional preconditions Post conditions Post conditions

040823040823 1616

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator DefinitionFor eg Operator definition for RATIONAL ADTFor eg Operator definition for RATIONAL ADT includes the operations of creation addition includes the operations of creation addition multiplication and equalitymultiplication and equality Now for multiplication operation the operator definition for Now for multiplication operation the operator definition for

RATIONAL ADT isRATIONAL ADT is Abstract RATIONAL mult(ab)helliphellipAbstract RATIONAL mult(ab)helliphellipheaderheader

RATIONAL a b helliphelliphellip RATIONAL a b helliphelliphellip header headermul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip mul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip postcondpostcond

mul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellipmul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellippostcondpostcond

040823040823 1717

Complete example of RATIONL Complete example of RATIONL ADTADT

value definition value definition Abstract typedefAbstract typedeflt int int gtRATIONALlt int int gtRATIONAL ConditionCondition RATIONAL[1]=0 RATIONAL[1]=0 Operator definition Operator definition Abstract equal(ab)Abstract equal(ab) RATIONAL a bRATIONAL a b Postcondition equal==(a[0]b[1]==b[0]b[1])Postcondition equal==(a[0]b[1]==b[0]b[1]) Like this we can declare the other operationsLike this we can declare the other operations

040823040823 1818

Classification of Data StructureClassification of Data Structure

Linear and Non-LinearLinear and Non-Linear

In linear data structure the data items are arranged In linear data structure the data items are arranged in linear sequence eg Array Stack Queue Linked in linear sequence eg Array Stack Queue Linked ListList

In non-linear data items are not in sequence eg In non-linear data items are not in sequence eg Tree graph HeapTree graph Heap

040823040823 1919

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Homogenous and Non-homogenousHomogenous and Non-homogenous

In homogenous data structure all the elements are In homogenous data structure all the elements are of same type eg Arrayof same type eg Array

In non-homogenous data structure the elements In non-homogenous data structure the elements may or may not be of same type eg Recordmay or may not be of same type eg Record

040823040823 2020

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Primitive and Non-PrimitivePrimitive and Non-PrimitivePrimitive data structures constitute thePrimitive data structures constitute thenumber and the characters which are builtnumber and the characters which are builtprograms examples int realspointer programs examples int realspointer datacharaters data logical data datacharaters data logical data

040823040823 2121

What is STACK or Pushdown What is STACK or Pushdown ListList

A ordered collection of items A ordered collection of items into which new items may be into which new items may be inserted and from which items inserted and from which items may be deleted at one end may be deleted at one end called the top of stack called the top of stack

040823040823 2222

Operations on STACKOperations on STACK

PUSHWhen item is added in stackPUSHWhen item is added in stack POPWhen item is removed from POPWhen item is removed from

stackstack EMPTYStack containing no itemsEMPTYStack containing no items StackTopDetermine what the top StackTopDetermine what the top

item on a stack without removing item on a stack without removing itthis is a combination of push amp popitthis is a combination of push amp pop

040823040823 2323

Push amp Pop in STACKPush amp Pop in STACK PUSH OperationPUSH Operation PUSHPUSH(STACK TOPMAXITEM) (STACK TOPMAXITEM) STACK--STACK--Name given to ArrayName given to Array TOP----TOP----It contains the location of top It contains the location of top

elementselements MAX---MAX---It is maximum size of STACKIt is maximum size of STACK ITEM---gtValue that is to be store in stack ITEM---gtValue that is to be store in stack

ifif top = MAX top = MAX thenthen stackfull stackfull top = top+1 top = top+1 stack(top) = item stack(top) = item ReturnReturn

040823040823 2424

Push amp Pop in STACKPush amp Pop in STACK

POP OperationPOP Operation

POPPOP(STACK TOPITEM) (STACK TOPITEM)

ifif top = 0 top = 0 thenthen Underflow Underflow item = stack(top) item = stack(top) top = top-1 top = top-1 Return Return

040823040823 2525

Applications of STACKApplications of STACK

Expression EvaluationExpression EvaluationParenthesis CheckerParenthesis CheckerRecursionRecursion

040823040823 2626

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

Operator preecedenceOperator preecedence^ ---------Higher precedence^ ---------Higher precedence--------Next Precedence--------Next Precedence+_-------Least precedence+_-------Least precedence

040823040823 2727

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

The rules to rememberThe rules to remember

11 Parenthesize the expression Parenthesize the expression starting fro left to rightstarting fro left to right

22 During Parenthesizing the During Parenthesizing the

expression the operands associatedexpression the operands associated

with operator having higher with operator having higher

precedence are first parenthesizedprecedence are first parenthesized

040823040823 2828

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

33 The sub-expression which has been The sub-expression which has been converted into postfix is to be converted into postfix is to be treated as single operandtreated as single operand

44 Once the expression is converted to Once the expression is converted to postfix form remove the postfix form remove the parenthesis parenthesis

Example A+BCExample A+BC A+[(B+C)+(D+E)F]GA+[(B+C)+(D+E)F]G Answer ABC+DE+F+G+Answer ABC+DE+F+G+

040823040823 2929

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

Postfix(QP)Postfix(QP) QmdashgtGiven Infix expressionQmdashgtGiven Infix expression P-gtEquivalent Postfix expressionP-gtEquivalent Postfix expression

11 Push ldquo(ldquo onto STACK and add ldquo)rdquo to the Push ldquo(ldquo onto STACK and add ldquo)rdquo to the end of Qend of Q

22 Scan Q from left to right and repeat step 3 Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK to 6 for each element of Q until the STACK is Emptyis Empty

33 If an operand is encountered add it to PIf an operand is encountered add it to P44 If a left parenthesis is encountered push If a left parenthesis is encountered push

it onto STACK it onto STACK

040823040823 3030

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

55 If an operator reg is encountered If an operator reg is encountered thenthen

(a) ADD reg to STACK(a) ADD reg to STACK

[End of IF][End of IF]

(b) Repeatedly pop from STACK and (b) Repeatedly pop from STACK and add P each operator which has add P each operator which has same precedence as or higher same precedence as or higher precedence than regprecedence than reg

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 7: Data structure

040823040823 77

Abstract Data Types(ADT)Abstract Data Types(ADT)

What is AbstractionWhat is AbstractionTo abstract is to ignore some detailsTo abstract is to ignore some detailsof a thing in favor of othersof a thing in favor of others

ADT amp Data structureADT amp Data structureAn An Abstract Data TypeAbstract Data Type (ADT) is more a way of (ADT) is more a way of

looking at a data structure focusing on what it looking at a data structure focusing on what it does and ignoring how it does its job does and ignoring how it does its job

040823040823 88

Abstract Data Types(ADT)Abstract Data Types(ADT)

Why need AbstractionWhy need AbstractionAbstraction is important in problem solving because Abstraction is important in problem solving because it allows problem solvers to focus on essential details it allows problem solvers to focus on essential details while ignoring the inessential thus simplifying the while ignoring the inessential thus simplifying the problem and bringing to attention those aspects of the problem and bringing to attention those aspects of the problem involved in its solution Once an abstract problem involved in its solution Once an abstract data type is understood and documented it serves as a data type is understood and documented it serves as a specification that programmers can use to guide their specification that programmers can use to guide their choice of data representation and operation choice of data representation and operation implementation and as a standard for ensuring implementation and as a standard for ensuring program correctness program correctness

040823040823 99

Abstract Data Types(ADT)Abstract Data Types(ADT)Abstract data typesAbstract data typesEach data structure can be developed around the Each data structure can be developed around the concept of an abstract data type that defines both dataconcept of an abstract data type that defines both dataorganization and data handling operationsorganization and data handling operations A mathematical entity consisting of a set of values A mathematical entity consisting of a set of values

and a collection of operations that manipulate them and a collection of operations that manipulate them For example the Integer abstract data type consists of For example the Integer abstract data type consists of a carrier set containing the positive and negative a carrier set containing the positive and negative whole numbers and 0 and a collection of operations whole numbers and 0 and a collection of operations manipulating these values such as addition manipulating these values such as addition subtraction multiplication equality comparison and subtraction multiplication equality comparison and order comparisonorder comparison

040823040823 1010

Abstract Data Types(ADT)Abstract Data Types(ADT) Abstract data types are important in computer science Abstract data types are important in computer science

because they provide a clear and precise way to because they provide a clear and precise way to specify what data a program must manipulate and specify what data a program must manipulate and how the program must manipulate its data without how the program must manipulate its data without regard to details about how data are represented or regard to details about how data are represented or how operations are implementedhow operations are implemented

ADT defines both data organization and data ADT defines both data organization and data handling operations handling operations

The study of data structure is organized around a The study of data structure is organized around a collection of abstract data types that includes lists collection of abstract data types that includes lists trees sets graphs and dictionaries trees sets graphs and dictionaries

040823040823 1111

Abstract Data Types(ADT)Abstract Data Types(ADT)

ADT is not a part of a program since a ADT is not a part of a program since a program written in a programming language program written in a programming language requires the definition of data structure not requires the definition of data structure not just the operations on the data structurejust the operations on the data structure

ADT is a useful tool for specifying the logical ADT is a useful tool for specifying the logical properties of a data typeproperties of a data type

ADT is not concerned with the timespace ADT is not concerned with the timespace efficiency of data typeefficiency of data type

040823040823 1212

Specification of ADTSpecification of ADT

ADT consist of 2 partsADT consist of 2 parts11 Value DefinitionValue Definition

22 Operator DefinitionOperator Definition

040823040823 1313

Specification of ADTSpecification of ADT

11 Value DefinitionValue DefinitionIt defines the collection of values for the It defines the collection of values for the ADT and consist of two partsADT and consist of two partsa)a) Definition Clause Definition Clause b)b) Condition ClauseCondition Clause eg For ADT RATIONAL eg For ADT RATIONAL Value definition it states that RATIONAL value Value definition it states that RATIONAL value consist of two integers the second of which does not equal consist of two integers the second of which does not equal to zeroto zeroThe keyword The keyword abstract typedefabstract typedef introduce a value definition introduce a value definition

040823040823 1414

Specification of ADTSpecification of ADT

Condition ClauseCondition Clause Used to specify any conditions on the newly defined Used to specify any conditions on the newly defined

typetype The keyword The keyword condition condition is used to specify any is used to specify any

conditions on the newly defined typeconditions on the newly defined typeFor eg for RATIONAL ADTFor eg for RATIONAL ADTCondition Clause denominator may not be zeroCondition Clause denominator may not be zeroNote The definition clause is required but the Note The definition clause is required but the condition clause may not be necessary for every condition clause may not be necessary for every ADTADT

040823040823 1515

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator Definition It defines the operations that are to be It defines the operations that are to be

performed on a data setperformed on a data set Each operator is defined as an abstract Each operator is defined as an abstract

function with three partsfunction with three parts HeaderHeader Optional preconditions Optional preconditions Post conditions Post conditions

040823040823 1616

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator DefinitionFor eg Operator definition for RATIONAL ADTFor eg Operator definition for RATIONAL ADT includes the operations of creation addition includes the operations of creation addition multiplication and equalitymultiplication and equality Now for multiplication operation the operator definition for Now for multiplication operation the operator definition for

RATIONAL ADT isRATIONAL ADT is Abstract RATIONAL mult(ab)helliphellipAbstract RATIONAL mult(ab)helliphellipheaderheader

RATIONAL a b helliphelliphellip RATIONAL a b helliphelliphellip header headermul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip mul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip postcondpostcond

mul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellipmul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellippostcondpostcond

040823040823 1717

Complete example of RATIONL Complete example of RATIONL ADTADT

value definition value definition Abstract typedefAbstract typedeflt int int gtRATIONALlt int int gtRATIONAL ConditionCondition RATIONAL[1]=0 RATIONAL[1]=0 Operator definition Operator definition Abstract equal(ab)Abstract equal(ab) RATIONAL a bRATIONAL a b Postcondition equal==(a[0]b[1]==b[0]b[1])Postcondition equal==(a[0]b[1]==b[0]b[1]) Like this we can declare the other operationsLike this we can declare the other operations

040823040823 1818

Classification of Data StructureClassification of Data Structure

Linear and Non-LinearLinear and Non-Linear

In linear data structure the data items are arranged In linear data structure the data items are arranged in linear sequence eg Array Stack Queue Linked in linear sequence eg Array Stack Queue Linked ListList

In non-linear data items are not in sequence eg In non-linear data items are not in sequence eg Tree graph HeapTree graph Heap

040823040823 1919

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Homogenous and Non-homogenousHomogenous and Non-homogenous

In homogenous data structure all the elements are In homogenous data structure all the elements are of same type eg Arrayof same type eg Array

In non-homogenous data structure the elements In non-homogenous data structure the elements may or may not be of same type eg Recordmay or may not be of same type eg Record

040823040823 2020

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Primitive and Non-PrimitivePrimitive and Non-PrimitivePrimitive data structures constitute thePrimitive data structures constitute thenumber and the characters which are builtnumber and the characters which are builtprograms examples int realspointer programs examples int realspointer datacharaters data logical data datacharaters data logical data

040823040823 2121

What is STACK or Pushdown What is STACK or Pushdown ListList

A ordered collection of items A ordered collection of items into which new items may be into which new items may be inserted and from which items inserted and from which items may be deleted at one end may be deleted at one end called the top of stack called the top of stack

040823040823 2222

Operations on STACKOperations on STACK

PUSHWhen item is added in stackPUSHWhen item is added in stack POPWhen item is removed from POPWhen item is removed from

stackstack EMPTYStack containing no itemsEMPTYStack containing no items StackTopDetermine what the top StackTopDetermine what the top

item on a stack without removing item on a stack without removing itthis is a combination of push amp popitthis is a combination of push amp pop

040823040823 2323

Push amp Pop in STACKPush amp Pop in STACK PUSH OperationPUSH Operation PUSHPUSH(STACK TOPMAXITEM) (STACK TOPMAXITEM) STACK--STACK--Name given to ArrayName given to Array TOP----TOP----It contains the location of top It contains the location of top

elementselements MAX---MAX---It is maximum size of STACKIt is maximum size of STACK ITEM---gtValue that is to be store in stack ITEM---gtValue that is to be store in stack

ifif top = MAX top = MAX thenthen stackfull stackfull top = top+1 top = top+1 stack(top) = item stack(top) = item ReturnReturn

040823040823 2424

Push amp Pop in STACKPush amp Pop in STACK

POP OperationPOP Operation

POPPOP(STACK TOPITEM) (STACK TOPITEM)

ifif top = 0 top = 0 thenthen Underflow Underflow item = stack(top) item = stack(top) top = top-1 top = top-1 Return Return

040823040823 2525

Applications of STACKApplications of STACK

Expression EvaluationExpression EvaluationParenthesis CheckerParenthesis CheckerRecursionRecursion

040823040823 2626

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

Operator preecedenceOperator preecedence^ ---------Higher precedence^ ---------Higher precedence--------Next Precedence--------Next Precedence+_-------Least precedence+_-------Least precedence

040823040823 2727

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

The rules to rememberThe rules to remember

11 Parenthesize the expression Parenthesize the expression starting fro left to rightstarting fro left to right

22 During Parenthesizing the During Parenthesizing the

expression the operands associatedexpression the operands associated

with operator having higher with operator having higher

precedence are first parenthesizedprecedence are first parenthesized

040823040823 2828

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

33 The sub-expression which has been The sub-expression which has been converted into postfix is to be converted into postfix is to be treated as single operandtreated as single operand

44 Once the expression is converted to Once the expression is converted to postfix form remove the postfix form remove the parenthesis parenthesis

Example A+BCExample A+BC A+[(B+C)+(D+E)F]GA+[(B+C)+(D+E)F]G Answer ABC+DE+F+G+Answer ABC+DE+F+G+

040823040823 2929

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

Postfix(QP)Postfix(QP) QmdashgtGiven Infix expressionQmdashgtGiven Infix expression P-gtEquivalent Postfix expressionP-gtEquivalent Postfix expression

11 Push ldquo(ldquo onto STACK and add ldquo)rdquo to the Push ldquo(ldquo onto STACK and add ldquo)rdquo to the end of Qend of Q

22 Scan Q from left to right and repeat step 3 Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK to 6 for each element of Q until the STACK is Emptyis Empty

33 If an operand is encountered add it to PIf an operand is encountered add it to P44 If a left parenthesis is encountered push If a left parenthesis is encountered push

it onto STACK it onto STACK

040823040823 3030

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

55 If an operator reg is encountered If an operator reg is encountered thenthen

(a) ADD reg to STACK(a) ADD reg to STACK

[End of IF][End of IF]

(b) Repeatedly pop from STACK and (b) Repeatedly pop from STACK and add P each operator which has add P each operator which has same precedence as or higher same precedence as or higher precedence than regprecedence than reg

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 8: Data structure

040823040823 88

Abstract Data Types(ADT)Abstract Data Types(ADT)

Why need AbstractionWhy need AbstractionAbstraction is important in problem solving because Abstraction is important in problem solving because it allows problem solvers to focus on essential details it allows problem solvers to focus on essential details while ignoring the inessential thus simplifying the while ignoring the inessential thus simplifying the problem and bringing to attention those aspects of the problem and bringing to attention those aspects of the problem involved in its solution Once an abstract problem involved in its solution Once an abstract data type is understood and documented it serves as a data type is understood and documented it serves as a specification that programmers can use to guide their specification that programmers can use to guide their choice of data representation and operation choice of data representation and operation implementation and as a standard for ensuring implementation and as a standard for ensuring program correctness program correctness

040823040823 99

Abstract Data Types(ADT)Abstract Data Types(ADT)Abstract data typesAbstract data typesEach data structure can be developed around the Each data structure can be developed around the concept of an abstract data type that defines both dataconcept of an abstract data type that defines both dataorganization and data handling operationsorganization and data handling operations A mathematical entity consisting of a set of values A mathematical entity consisting of a set of values

and a collection of operations that manipulate them and a collection of operations that manipulate them For example the Integer abstract data type consists of For example the Integer abstract data type consists of a carrier set containing the positive and negative a carrier set containing the positive and negative whole numbers and 0 and a collection of operations whole numbers and 0 and a collection of operations manipulating these values such as addition manipulating these values such as addition subtraction multiplication equality comparison and subtraction multiplication equality comparison and order comparisonorder comparison

040823040823 1010

Abstract Data Types(ADT)Abstract Data Types(ADT) Abstract data types are important in computer science Abstract data types are important in computer science

because they provide a clear and precise way to because they provide a clear and precise way to specify what data a program must manipulate and specify what data a program must manipulate and how the program must manipulate its data without how the program must manipulate its data without regard to details about how data are represented or regard to details about how data are represented or how operations are implementedhow operations are implemented

ADT defines both data organization and data ADT defines both data organization and data handling operations handling operations

The study of data structure is organized around a The study of data structure is organized around a collection of abstract data types that includes lists collection of abstract data types that includes lists trees sets graphs and dictionaries trees sets graphs and dictionaries

040823040823 1111

Abstract Data Types(ADT)Abstract Data Types(ADT)

ADT is not a part of a program since a ADT is not a part of a program since a program written in a programming language program written in a programming language requires the definition of data structure not requires the definition of data structure not just the operations on the data structurejust the operations on the data structure

ADT is a useful tool for specifying the logical ADT is a useful tool for specifying the logical properties of a data typeproperties of a data type

ADT is not concerned with the timespace ADT is not concerned with the timespace efficiency of data typeefficiency of data type

040823040823 1212

Specification of ADTSpecification of ADT

ADT consist of 2 partsADT consist of 2 parts11 Value DefinitionValue Definition

22 Operator DefinitionOperator Definition

040823040823 1313

Specification of ADTSpecification of ADT

11 Value DefinitionValue DefinitionIt defines the collection of values for the It defines the collection of values for the ADT and consist of two partsADT and consist of two partsa)a) Definition Clause Definition Clause b)b) Condition ClauseCondition Clause eg For ADT RATIONAL eg For ADT RATIONAL Value definition it states that RATIONAL value Value definition it states that RATIONAL value consist of two integers the second of which does not equal consist of two integers the second of which does not equal to zeroto zeroThe keyword The keyword abstract typedefabstract typedef introduce a value definition introduce a value definition

040823040823 1414

Specification of ADTSpecification of ADT

Condition ClauseCondition Clause Used to specify any conditions on the newly defined Used to specify any conditions on the newly defined

typetype The keyword The keyword condition condition is used to specify any is used to specify any

conditions on the newly defined typeconditions on the newly defined typeFor eg for RATIONAL ADTFor eg for RATIONAL ADTCondition Clause denominator may not be zeroCondition Clause denominator may not be zeroNote The definition clause is required but the Note The definition clause is required but the condition clause may not be necessary for every condition clause may not be necessary for every ADTADT

040823040823 1515

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator Definition It defines the operations that are to be It defines the operations that are to be

performed on a data setperformed on a data set Each operator is defined as an abstract Each operator is defined as an abstract

function with three partsfunction with three parts HeaderHeader Optional preconditions Optional preconditions Post conditions Post conditions

040823040823 1616

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator DefinitionFor eg Operator definition for RATIONAL ADTFor eg Operator definition for RATIONAL ADT includes the operations of creation addition includes the operations of creation addition multiplication and equalitymultiplication and equality Now for multiplication operation the operator definition for Now for multiplication operation the operator definition for

RATIONAL ADT isRATIONAL ADT is Abstract RATIONAL mult(ab)helliphellipAbstract RATIONAL mult(ab)helliphellipheaderheader

RATIONAL a b helliphelliphellip RATIONAL a b helliphelliphellip header headermul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip mul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip postcondpostcond

mul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellipmul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellippostcondpostcond

040823040823 1717

Complete example of RATIONL Complete example of RATIONL ADTADT

value definition value definition Abstract typedefAbstract typedeflt int int gtRATIONALlt int int gtRATIONAL ConditionCondition RATIONAL[1]=0 RATIONAL[1]=0 Operator definition Operator definition Abstract equal(ab)Abstract equal(ab) RATIONAL a bRATIONAL a b Postcondition equal==(a[0]b[1]==b[0]b[1])Postcondition equal==(a[0]b[1]==b[0]b[1]) Like this we can declare the other operationsLike this we can declare the other operations

040823040823 1818

Classification of Data StructureClassification of Data Structure

Linear and Non-LinearLinear and Non-Linear

In linear data structure the data items are arranged In linear data structure the data items are arranged in linear sequence eg Array Stack Queue Linked in linear sequence eg Array Stack Queue Linked ListList

In non-linear data items are not in sequence eg In non-linear data items are not in sequence eg Tree graph HeapTree graph Heap

040823040823 1919

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Homogenous and Non-homogenousHomogenous and Non-homogenous

In homogenous data structure all the elements are In homogenous data structure all the elements are of same type eg Arrayof same type eg Array

In non-homogenous data structure the elements In non-homogenous data structure the elements may or may not be of same type eg Recordmay or may not be of same type eg Record

040823040823 2020

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Primitive and Non-PrimitivePrimitive and Non-PrimitivePrimitive data structures constitute thePrimitive data structures constitute thenumber and the characters which are builtnumber and the characters which are builtprograms examples int realspointer programs examples int realspointer datacharaters data logical data datacharaters data logical data

040823040823 2121

What is STACK or Pushdown What is STACK or Pushdown ListList

A ordered collection of items A ordered collection of items into which new items may be into which new items may be inserted and from which items inserted and from which items may be deleted at one end may be deleted at one end called the top of stack called the top of stack

040823040823 2222

Operations on STACKOperations on STACK

PUSHWhen item is added in stackPUSHWhen item is added in stack POPWhen item is removed from POPWhen item is removed from

stackstack EMPTYStack containing no itemsEMPTYStack containing no items StackTopDetermine what the top StackTopDetermine what the top

item on a stack without removing item on a stack without removing itthis is a combination of push amp popitthis is a combination of push amp pop

040823040823 2323

Push amp Pop in STACKPush amp Pop in STACK PUSH OperationPUSH Operation PUSHPUSH(STACK TOPMAXITEM) (STACK TOPMAXITEM) STACK--STACK--Name given to ArrayName given to Array TOP----TOP----It contains the location of top It contains the location of top

elementselements MAX---MAX---It is maximum size of STACKIt is maximum size of STACK ITEM---gtValue that is to be store in stack ITEM---gtValue that is to be store in stack

ifif top = MAX top = MAX thenthen stackfull stackfull top = top+1 top = top+1 stack(top) = item stack(top) = item ReturnReturn

040823040823 2424

Push amp Pop in STACKPush amp Pop in STACK

POP OperationPOP Operation

POPPOP(STACK TOPITEM) (STACK TOPITEM)

ifif top = 0 top = 0 thenthen Underflow Underflow item = stack(top) item = stack(top) top = top-1 top = top-1 Return Return

040823040823 2525

Applications of STACKApplications of STACK

Expression EvaluationExpression EvaluationParenthesis CheckerParenthesis CheckerRecursionRecursion

040823040823 2626

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

Operator preecedenceOperator preecedence^ ---------Higher precedence^ ---------Higher precedence--------Next Precedence--------Next Precedence+_-------Least precedence+_-------Least precedence

040823040823 2727

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

The rules to rememberThe rules to remember

11 Parenthesize the expression Parenthesize the expression starting fro left to rightstarting fro left to right

22 During Parenthesizing the During Parenthesizing the

expression the operands associatedexpression the operands associated

with operator having higher with operator having higher

precedence are first parenthesizedprecedence are first parenthesized

040823040823 2828

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

33 The sub-expression which has been The sub-expression which has been converted into postfix is to be converted into postfix is to be treated as single operandtreated as single operand

44 Once the expression is converted to Once the expression is converted to postfix form remove the postfix form remove the parenthesis parenthesis

Example A+BCExample A+BC A+[(B+C)+(D+E)F]GA+[(B+C)+(D+E)F]G Answer ABC+DE+F+G+Answer ABC+DE+F+G+

040823040823 2929

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

Postfix(QP)Postfix(QP) QmdashgtGiven Infix expressionQmdashgtGiven Infix expression P-gtEquivalent Postfix expressionP-gtEquivalent Postfix expression

11 Push ldquo(ldquo onto STACK and add ldquo)rdquo to the Push ldquo(ldquo onto STACK and add ldquo)rdquo to the end of Qend of Q

22 Scan Q from left to right and repeat step 3 Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK to 6 for each element of Q until the STACK is Emptyis Empty

33 If an operand is encountered add it to PIf an operand is encountered add it to P44 If a left parenthesis is encountered push If a left parenthesis is encountered push

it onto STACK it onto STACK

040823040823 3030

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

55 If an operator reg is encountered If an operator reg is encountered thenthen

(a) ADD reg to STACK(a) ADD reg to STACK

[End of IF][End of IF]

(b) Repeatedly pop from STACK and (b) Repeatedly pop from STACK and add P each operator which has add P each operator which has same precedence as or higher same precedence as or higher precedence than regprecedence than reg

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 9: Data structure

040823040823 99

Abstract Data Types(ADT)Abstract Data Types(ADT)Abstract data typesAbstract data typesEach data structure can be developed around the Each data structure can be developed around the concept of an abstract data type that defines both dataconcept of an abstract data type that defines both dataorganization and data handling operationsorganization and data handling operations A mathematical entity consisting of a set of values A mathematical entity consisting of a set of values

and a collection of operations that manipulate them and a collection of operations that manipulate them For example the Integer abstract data type consists of For example the Integer abstract data type consists of a carrier set containing the positive and negative a carrier set containing the positive and negative whole numbers and 0 and a collection of operations whole numbers and 0 and a collection of operations manipulating these values such as addition manipulating these values such as addition subtraction multiplication equality comparison and subtraction multiplication equality comparison and order comparisonorder comparison

040823040823 1010

Abstract Data Types(ADT)Abstract Data Types(ADT) Abstract data types are important in computer science Abstract data types are important in computer science

because they provide a clear and precise way to because they provide a clear and precise way to specify what data a program must manipulate and specify what data a program must manipulate and how the program must manipulate its data without how the program must manipulate its data without regard to details about how data are represented or regard to details about how data are represented or how operations are implementedhow operations are implemented

ADT defines both data organization and data ADT defines both data organization and data handling operations handling operations

The study of data structure is organized around a The study of data structure is organized around a collection of abstract data types that includes lists collection of abstract data types that includes lists trees sets graphs and dictionaries trees sets graphs and dictionaries

040823040823 1111

Abstract Data Types(ADT)Abstract Data Types(ADT)

ADT is not a part of a program since a ADT is not a part of a program since a program written in a programming language program written in a programming language requires the definition of data structure not requires the definition of data structure not just the operations on the data structurejust the operations on the data structure

ADT is a useful tool for specifying the logical ADT is a useful tool for specifying the logical properties of a data typeproperties of a data type

ADT is not concerned with the timespace ADT is not concerned with the timespace efficiency of data typeefficiency of data type

040823040823 1212

Specification of ADTSpecification of ADT

ADT consist of 2 partsADT consist of 2 parts11 Value DefinitionValue Definition

22 Operator DefinitionOperator Definition

040823040823 1313

Specification of ADTSpecification of ADT

11 Value DefinitionValue DefinitionIt defines the collection of values for the It defines the collection of values for the ADT and consist of two partsADT and consist of two partsa)a) Definition Clause Definition Clause b)b) Condition ClauseCondition Clause eg For ADT RATIONAL eg For ADT RATIONAL Value definition it states that RATIONAL value Value definition it states that RATIONAL value consist of two integers the second of which does not equal consist of two integers the second of which does not equal to zeroto zeroThe keyword The keyword abstract typedefabstract typedef introduce a value definition introduce a value definition

040823040823 1414

Specification of ADTSpecification of ADT

Condition ClauseCondition Clause Used to specify any conditions on the newly defined Used to specify any conditions on the newly defined

typetype The keyword The keyword condition condition is used to specify any is used to specify any

conditions on the newly defined typeconditions on the newly defined typeFor eg for RATIONAL ADTFor eg for RATIONAL ADTCondition Clause denominator may not be zeroCondition Clause denominator may not be zeroNote The definition clause is required but the Note The definition clause is required but the condition clause may not be necessary for every condition clause may not be necessary for every ADTADT

040823040823 1515

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator Definition It defines the operations that are to be It defines the operations that are to be

performed on a data setperformed on a data set Each operator is defined as an abstract Each operator is defined as an abstract

function with three partsfunction with three parts HeaderHeader Optional preconditions Optional preconditions Post conditions Post conditions

040823040823 1616

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator DefinitionFor eg Operator definition for RATIONAL ADTFor eg Operator definition for RATIONAL ADT includes the operations of creation addition includes the operations of creation addition multiplication and equalitymultiplication and equality Now for multiplication operation the operator definition for Now for multiplication operation the operator definition for

RATIONAL ADT isRATIONAL ADT is Abstract RATIONAL mult(ab)helliphellipAbstract RATIONAL mult(ab)helliphellipheaderheader

RATIONAL a b helliphelliphellip RATIONAL a b helliphelliphellip header headermul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip mul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip postcondpostcond

mul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellipmul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellippostcondpostcond

040823040823 1717

Complete example of RATIONL Complete example of RATIONL ADTADT

value definition value definition Abstract typedefAbstract typedeflt int int gtRATIONALlt int int gtRATIONAL ConditionCondition RATIONAL[1]=0 RATIONAL[1]=0 Operator definition Operator definition Abstract equal(ab)Abstract equal(ab) RATIONAL a bRATIONAL a b Postcondition equal==(a[0]b[1]==b[0]b[1])Postcondition equal==(a[0]b[1]==b[0]b[1]) Like this we can declare the other operationsLike this we can declare the other operations

040823040823 1818

Classification of Data StructureClassification of Data Structure

Linear and Non-LinearLinear and Non-Linear

In linear data structure the data items are arranged In linear data structure the data items are arranged in linear sequence eg Array Stack Queue Linked in linear sequence eg Array Stack Queue Linked ListList

In non-linear data items are not in sequence eg In non-linear data items are not in sequence eg Tree graph HeapTree graph Heap

040823040823 1919

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Homogenous and Non-homogenousHomogenous and Non-homogenous

In homogenous data structure all the elements are In homogenous data structure all the elements are of same type eg Arrayof same type eg Array

In non-homogenous data structure the elements In non-homogenous data structure the elements may or may not be of same type eg Recordmay or may not be of same type eg Record

040823040823 2020

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Primitive and Non-PrimitivePrimitive and Non-PrimitivePrimitive data structures constitute thePrimitive data structures constitute thenumber and the characters which are builtnumber and the characters which are builtprograms examples int realspointer programs examples int realspointer datacharaters data logical data datacharaters data logical data

040823040823 2121

What is STACK or Pushdown What is STACK or Pushdown ListList

A ordered collection of items A ordered collection of items into which new items may be into which new items may be inserted and from which items inserted and from which items may be deleted at one end may be deleted at one end called the top of stack called the top of stack

040823040823 2222

Operations on STACKOperations on STACK

PUSHWhen item is added in stackPUSHWhen item is added in stack POPWhen item is removed from POPWhen item is removed from

stackstack EMPTYStack containing no itemsEMPTYStack containing no items StackTopDetermine what the top StackTopDetermine what the top

item on a stack without removing item on a stack without removing itthis is a combination of push amp popitthis is a combination of push amp pop

040823040823 2323

Push amp Pop in STACKPush amp Pop in STACK PUSH OperationPUSH Operation PUSHPUSH(STACK TOPMAXITEM) (STACK TOPMAXITEM) STACK--STACK--Name given to ArrayName given to Array TOP----TOP----It contains the location of top It contains the location of top

elementselements MAX---MAX---It is maximum size of STACKIt is maximum size of STACK ITEM---gtValue that is to be store in stack ITEM---gtValue that is to be store in stack

ifif top = MAX top = MAX thenthen stackfull stackfull top = top+1 top = top+1 stack(top) = item stack(top) = item ReturnReturn

040823040823 2424

Push amp Pop in STACKPush amp Pop in STACK

POP OperationPOP Operation

POPPOP(STACK TOPITEM) (STACK TOPITEM)

ifif top = 0 top = 0 thenthen Underflow Underflow item = stack(top) item = stack(top) top = top-1 top = top-1 Return Return

040823040823 2525

Applications of STACKApplications of STACK

Expression EvaluationExpression EvaluationParenthesis CheckerParenthesis CheckerRecursionRecursion

040823040823 2626

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

Operator preecedenceOperator preecedence^ ---------Higher precedence^ ---------Higher precedence--------Next Precedence--------Next Precedence+_-------Least precedence+_-------Least precedence

040823040823 2727

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

The rules to rememberThe rules to remember

11 Parenthesize the expression Parenthesize the expression starting fro left to rightstarting fro left to right

22 During Parenthesizing the During Parenthesizing the

expression the operands associatedexpression the operands associated

with operator having higher with operator having higher

precedence are first parenthesizedprecedence are first parenthesized

040823040823 2828

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

33 The sub-expression which has been The sub-expression which has been converted into postfix is to be converted into postfix is to be treated as single operandtreated as single operand

44 Once the expression is converted to Once the expression is converted to postfix form remove the postfix form remove the parenthesis parenthesis

Example A+BCExample A+BC A+[(B+C)+(D+E)F]GA+[(B+C)+(D+E)F]G Answer ABC+DE+F+G+Answer ABC+DE+F+G+

040823040823 2929

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

Postfix(QP)Postfix(QP) QmdashgtGiven Infix expressionQmdashgtGiven Infix expression P-gtEquivalent Postfix expressionP-gtEquivalent Postfix expression

11 Push ldquo(ldquo onto STACK and add ldquo)rdquo to the Push ldquo(ldquo onto STACK and add ldquo)rdquo to the end of Qend of Q

22 Scan Q from left to right and repeat step 3 Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK to 6 for each element of Q until the STACK is Emptyis Empty

33 If an operand is encountered add it to PIf an operand is encountered add it to P44 If a left parenthesis is encountered push If a left parenthesis is encountered push

it onto STACK it onto STACK

040823040823 3030

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

55 If an operator reg is encountered If an operator reg is encountered thenthen

(a) ADD reg to STACK(a) ADD reg to STACK

[End of IF][End of IF]

(b) Repeatedly pop from STACK and (b) Repeatedly pop from STACK and add P each operator which has add P each operator which has same precedence as or higher same precedence as or higher precedence than regprecedence than reg

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 10: Data structure

040823040823 1010

Abstract Data Types(ADT)Abstract Data Types(ADT) Abstract data types are important in computer science Abstract data types are important in computer science

because they provide a clear and precise way to because they provide a clear and precise way to specify what data a program must manipulate and specify what data a program must manipulate and how the program must manipulate its data without how the program must manipulate its data without regard to details about how data are represented or regard to details about how data are represented or how operations are implementedhow operations are implemented

ADT defines both data organization and data ADT defines both data organization and data handling operations handling operations

The study of data structure is organized around a The study of data structure is organized around a collection of abstract data types that includes lists collection of abstract data types that includes lists trees sets graphs and dictionaries trees sets graphs and dictionaries

040823040823 1111

Abstract Data Types(ADT)Abstract Data Types(ADT)

ADT is not a part of a program since a ADT is not a part of a program since a program written in a programming language program written in a programming language requires the definition of data structure not requires the definition of data structure not just the operations on the data structurejust the operations on the data structure

ADT is a useful tool for specifying the logical ADT is a useful tool for specifying the logical properties of a data typeproperties of a data type

ADT is not concerned with the timespace ADT is not concerned with the timespace efficiency of data typeefficiency of data type

040823040823 1212

Specification of ADTSpecification of ADT

ADT consist of 2 partsADT consist of 2 parts11 Value DefinitionValue Definition

22 Operator DefinitionOperator Definition

040823040823 1313

Specification of ADTSpecification of ADT

11 Value DefinitionValue DefinitionIt defines the collection of values for the It defines the collection of values for the ADT and consist of two partsADT and consist of two partsa)a) Definition Clause Definition Clause b)b) Condition ClauseCondition Clause eg For ADT RATIONAL eg For ADT RATIONAL Value definition it states that RATIONAL value Value definition it states that RATIONAL value consist of two integers the second of which does not equal consist of two integers the second of which does not equal to zeroto zeroThe keyword The keyword abstract typedefabstract typedef introduce a value definition introduce a value definition

040823040823 1414

Specification of ADTSpecification of ADT

Condition ClauseCondition Clause Used to specify any conditions on the newly defined Used to specify any conditions on the newly defined

typetype The keyword The keyword condition condition is used to specify any is used to specify any

conditions on the newly defined typeconditions on the newly defined typeFor eg for RATIONAL ADTFor eg for RATIONAL ADTCondition Clause denominator may not be zeroCondition Clause denominator may not be zeroNote The definition clause is required but the Note The definition clause is required but the condition clause may not be necessary for every condition clause may not be necessary for every ADTADT

040823040823 1515

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator Definition It defines the operations that are to be It defines the operations that are to be

performed on a data setperformed on a data set Each operator is defined as an abstract Each operator is defined as an abstract

function with three partsfunction with three parts HeaderHeader Optional preconditions Optional preconditions Post conditions Post conditions

040823040823 1616

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator DefinitionFor eg Operator definition for RATIONAL ADTFor eg Operator definition for RATIONAL ADT includes the operations of creation addition includes the operations of creation addition multiplication and equalitymultiplication and equality Now for multiplication operation the operator definition for Now for multiplication operation the operator definition for

RATIONAL ADT isRATIONAL ADT is Abstract RATIONAL mult(ab)helliphellipAbstract RATIONAL mult(ab)helliphellipheaderheader

RATIONAL a b helliphelliphellip RATIONAL a b helliphelliphellip header headermul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip mul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip postcondpostcond

mul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellipmul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellippostcondpostcond

040823040823 1717

Complete example of RATIONL Complete example of RATIONL ADTADT

value definition value definition Abstract typedefAbstract typedeflt int int gtRATIONALlt int int gtRATIONAL ConditionCondition RATIONAL[1]=0 RATIONAL[1]=0 Operator definition Operator definition Abstract equal(ab)Abstract equal(ab) RATIONAL a bRATIONAL a b Postcondition equal==(a[0]b[1]==b[0]b[1])Postcondition equal==(a[0]b[1]==b[0]b[1]) Like this we can declare the other operationsLike this we can declare the other operations

040823040823 1818

Classification of Data StructureClassification of Data Structure

Linear and Non-LinearLinear and Non-Linear

In linear data structure the data items are arranged In linear data structure the data items are arranged in linear sequence eg Array Stack Queue Linked in linear sequence eg Array Stack Queue Linked ListList

In non-linear data items are not in sequence eg In non-linear data items are not in sequence eg Tree graph HeapTree graph Heap

040823040823 1919

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Homogenous and Non-homogenousHomogenous and Non-homogenous

In homogenous data structure all the elements are In homogenous data structure all the elements are of same type eg Arrayof same type eg Array

In non-homogenous data structure the elements In non-homogenous data structure the elements may or may not be of same type eg Recordmay or may not be of same type eg Record

040823040823 2020

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Primitive and Non-PrimitivePrimitive and Non-PrimitivePrimitive data structures constitute thePrimitive data structures constitute thenumber and the characters which are builtnumber and the characters which are builtprograms examples int realspointer programs examples int realspointer datacharaters data logical data datacharaters data logical data

040823040823 2121

What is STACK or Pushdown What is STACK or Pushdown ListList

A ordered collection of items A ordered collection of items into which new items may be into which new items may be inserted and from which items inserted and from which items may be deleted at one end may be deleted at one end called the top of stack called the top of stack

040823040823 2222

Operations on STACKOperations on STACK

PUSHWhen item is added in stackPUSHWhen item is added in stack POPWhen item is removed from POPWhen item is removed from

stackstack EMPTYStack containing no itemsEMPTYStack containing no items StackTopDetermine what the top StackTopDetermine what the top

item on a stack without removing item on a stack without removing itthis is a combination of push amp popitthis is a combination of push amp pop

040823040823 2323

Push amp Pop in STACKPush amp Pop in STACK PUSH OperationPUSH Operation PUSHPUSH(STACK TOPMAXITEM) (STACK TOPMAXITEM) STACK--STACK--Name given to ArrayName given to Array TOP----TOP----It contains the location of top It contains the location of top

elementselements MAX---MAX---It is maximum size of STACKIt is maximum size of STACK ITEM---gtValue that is to be store in stack ITEM---gtValue that is to be store in stack

ifif top = MAX top = MAX thenthen stackfull stackfull top = top+1 top = top+1 stack(top) = item stack(top) = item ReturnReturn

040823040823 2424

Push amp Pop in STACKPush amp Pop in STACK

POP OperationPOP Operation

POPPOP(STACK TOPITEM) (STACK TOPITEM)

ifif top = 0 top = 0 thenthen Underflow Underflow item = stack(top) item = stack(top) top = top-1 top = top-1 Return Return

040823040823 2525

Applications of STACKApplications of STACK

Expression EvaluationExpression EvaluationParenthesis CheckerParenthesis CheckerRecursionRecursion

040823040823 2626

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

Operator preecedenceOperator preecedence^ ---------Higher precedence^ ---------Higher precedence--------Next Precedence--------Next Precedence+_-------Least precedence+_-------Least precedence

040823040823 2727

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

The rules to rememberThe rules to remember

11 Parenthesize the expression Parenthesize the expression starting fro left to rightstarting fro left to right

22 During Parenthesizing the During Parenthesizing the

expression the operands associatedexpression the operands associated

with operator having higher with operator having higher

precedence are first parenthesizedprecedence are first parenthesized

040823040823 2828

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

33 The sub-expression which has been The sub-expression which has been converted into postfix is to be converted into postfix is to be treated as single operandtreated as single operand

44 Once the expression is converted to Once the expression is converted to postfix form remove the postfix form remove the parenthesis parenthesis

Example A+BCExample A+BC A+[(B+C)+(D+E)F]GA+[(B+C)+(D+E)F]G Answer ABC+DE+F+G+Answer ABC+DE+F+G+

040823040823 2929

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

Postfix(QP)Postfix(QP) QmdashgtGiven Infix expressionQmdashgtGiven Infix expression P-gtEquivalent Postfix expressionP-gtEquivalent Postfix expression

11 Push ldquo(ldquo onto STACK and add ldquo)rdquo to the Push ldquo(ldquo onto STACK and add ldquo)rdquo to the end of Qend of Q

22 Scan Q from left to right and repeat step 3 Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK to 6 for each element of Q until the STACK is Emptyis Empty

33 If an operand is encountered add it to PIf an operand is encountered add it to P44 If a left parenthesis is encountered push If a left parenthesis is encountered push

it onto STACK it onto STACK

040823040823 3030

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

55 If an operator reg is encountered If an operator reg is encountered thenthen

(a) ADD reg to STACK(a) ADD reg to STACK

[End of IF][End of IF]

(b) Repeatedly pop from STACK and (b) Repeatedly pop from STACK and add P each operator which has add P each operator which has same precedence as or higher same precedence as or higher precedence than regprecedence than reg

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 11: Data structure

040823040823 1111

Abstract Data Types(ADT)Abstract Data Types(ADT)

ADT is not a part of a program since a ADT is not a part of a program since a program written in a programming language program written in a programming language requires the definition of data structure not requires the definition of data structure not just the operations on the data structurejust the operations on the data structure

ADT is a useful tool for specifying the logical ADT is a useful tool for specifying the logical properties of a data typeproperties of a data type

ADT is not concerned with the timespace ADT is not concerned with the timespace efficiency of data typeefficiency of data type

040823040823 1212

Specification of ADTSpecification of ADT

ADT consist of 2 partsADT consist of 2 parts11 Value DefinitionValue Definition

22 Operator DefinitionOperator Definition

040823040823 1313

Specification of ADTSpecification of ADT

11 Value DefinitionValue DefinitionIt defines the collection of values for the It defines the collection of values for the ADT and consist of two partsADT and consist of two partsa)a) Definition Clause Definition Clause b)b) Condition ClauseCondition Clause eg For ADT RATIONAL eg For ADT RATIONAL Value definition it states that RATIONAL value Value definition it states that RATIONAL value consist of two integers the second of which does not equal consist of two integers the second of which does not equal to zeroto zeroThe keyword The keyword abstract typedefabstract typedef introduce a value definition introduce a value definition

040823040823 1414

Specification of ADTSpecification of ADT

Condition ClauseCondition Clause Used to specify any conditions on the newly defined Used to specify any conditions on the newly defined

typetype The keyword The keyword condition condition is used to specify any is used to specify any

conditions on the newly defined typeconditions on the newly defined typeFor eg for RATIONAL ADTFor eg for RATIONAL ADTCondition Clause denominator may not be zeroCondition Clause denominator may not be zeroNote The definition clause is required but the Note The definition clause is required but the condition clause may not be necessary for every condition clause may not be necessary for every ADTADT

040823040823 1515

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator Definition It defines the operations that are to be It defines the operations that are to be

performed on a data setperformed on a data set Each operator is defined as an abstract Each operator is defined as an abstract

function with three partsfunction with three parts HeaderHeader Optional preconditions Optional preconditions Post conditions Post conditions

040823040823 1616

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator DefinitionFor eg Operator definition for RATIONAL ADTFor eg Operator definition for RATIONAL ADT includes the operations of creation addition includes the operations of creation addition multiplication and equalitymultiplication and equality Now for multiplication operation the operator definition for Now for multiplication operation the operator definition for

RATIONAL ADT isRATIONAL ADT is Abstract RATIONAL mult(ab)helliphellipAbstract RATIONAL mult(ab)helliphellipheaderheader

RATIONAL a b helliphelliphellip RATIONAL a b helliphelliphellip header headermul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip mul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip postcondpostcond

mul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellipmul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellippostcondpostcond

040823040823 1717

Complete example of RATIONL Complete example of RATIONL ADTADT

value definition value definition Abstract typedefAbstract typedeflt int int gtRATIONALlt int int gtRATIONAL ConditionCondition RATIONAL[1]=0 RATIONAL[1]=0 Operator definition Operator definition Abstract equal(ab)Abstract equal(ab) RATIONAL a bRATIONAL a b Postcondition equal==(a[0]b[1]==b[0]b[1])Postcondition equal==(a[0]b[1]==b[0]b[1]) Like this we can declare the other operationsLike this we can declare the other operations

040823040823 1818

Classification of Data StructureClassification of Data Structure

Linear and Non-LinearLinear and Non-Linear

In linear data structure the data items are arranged In linear data structure the data items are arranged in linear sequence eg Array Stack Queue Linked in linear sequence eg Array Stack Queue Linked ListList

In non-linear data items are not in sequence eg In non-linear data items are not in sequence eg Tree graph HeapTree graph Heap

040823040823 1919

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Homogenous and Non-homogenousHomogenous and Non-homogenous

In homogenous data structure all the elements are In homogenous data structure all the elements are of same type eg Arrayof same type eg Array

In non-homogenous data structure the elements In non-homogenous data structure the elements may or may not be of same type eg Recordmay or may not be of same type eg Record

040823040823 2020

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Primitive and Non-PrimitivePrimitive and Non-PrimitivePrimitive data structures constitute thePrimitive data structures constitute thenumber and the characters which are builtnumber and the characters which are builtprograms examples int realspointer programs examples int realspointer datacharaters data logical data datacharaters data logical data

040823040823 2121

What is STACK or Pushdown What is STACK or Pushdown ListList

A ordered collection of items A ordered collection of items into which new items may be into which new items may be inserted and from which items inserted and from which items may be deleted at one end may be deleted at one end called the top of stack called the top of stack

040823040823 2222

Operations on STACKOperations on STACK

PUSHWhen item is added in stackPUSHWhen item is added in stack POPWhen item is removed from POPWhen item is removed from

stackstack EMPTYStack containing no itemsEMPTYStack containing no items StackTopDetermine what the top StackTopDetermine what the top

item on a stack without removing item on a stack without removing itthis is a combination of push amp popitthis is a combination of push amp pop

040823040823 2323

Push amp Pop in STACKPush amp Pop in STACK PUSH OperationPUSH Operation PUSHPUSH(STACK TOPMAXITEM) (STACK TOPMAXITEM) STACK--STACK--Name given to ArrayName given to Array TOP----TOP----It contains the location of top It contains the location of top

elementselements MAX---MAX---It is maximum size of STACKIt is maximum size of STACK ITEM---gtValue that is to be store in stack ITEM---gtValue that is to be store in stack

ifif top = MAX top = MAX thenthen stackfull stackfull top = top+1 top = top+1 stack(top) = item stack(top) = item ReturnReturn

040823040823 2424

Push amp Pop in STACKPush amp Pop in STACK

POP OperationPOP Operation

POPPOP(STACK TOPITEM) (STACK TOPITEM)

ifif top = 0 top = 0 thenthen Underflow Underflow item = stack(top) item = stack(top) top = top-1 top = top-1 Return Return

040823040823 2525

Applications of STACKApplications of STACK

Expression EvaluationExpression EvaluationParenthesis CheckerParenthesis CheckerRecursionRecursion

040823040823 2626

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

Operator preecedenceOperator preecedence^ ---------Higher precedence^ ---------Higher precedence--------Next Precedence--------Next Precedence+_-------Least precedence+_-------Least precedence

040823040823 2727

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

The rules to rememberThe rules to remember

11 Parenthesize the expression Parenthesize the expression starting fro left to rightstarting fro left to right

22 During Parenthesizing the During Parenthesizing the

expression the operands associatedexpression the operands associated

with operator having higher with operator having higher

precedence are first parenthesizedprecedence are first parenthesized

040823040823 2828

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

33 The sub-expression which has been The sub-expression which has been converted into postfix is to be converted into postfix is to be treated as single operandtreated as single operand

44 Once the expression is converted to Once the expression is converted to postfix form remove the postfix form remove the parenthesis parenthesis

Example A+BCExample A+BC A+[(B+C)+(D+E)F]GA+[(B+C)+(D+E)F]G Answer ABC+DE+F+G+Answer ABC+DE+F+G+

040823040823 2929

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

Postfix(QP)Postfix(QP) QmdashgtGiven Infix expressionQmdashgtGiven Infix expression P-gtEquivalent Postfix expressionP-gtEquivalent Postfix expression

11 Push ldquo(ldquo onto STACK and add ldquo)rdquo to the Push ldquo(ldquo onto STACK and add ldquo)rdquo to the end of Qend of Q

22 Scan Q from left to right and repeat step 3 Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK to 6 for each element of Q until the STACK is Emptyis Empty

33 If an operand is encountered add it to PIf an operand is encountered add it to P44 If a left parenthesis is encountered push If a left parenthesis is encountered push

it onto STACK it onto STACK

040823040823 3030

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

55 If an operator reg is encountered If an operator reg is encountered thenthen

(a) ADD reg to STACK(a) ADD reg to STACK

[End of IF][End of IF]

(b) Repeatedly pop from STACK and (b) Repeatedly pop from STACK and add P each operator which has add P each operator which has same precedence as or higher same precedence as or higher precedence than regprecedence than reg

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 12: Data structure

040823040823 1212

Specification of ADTSpecification of ADT

ADT consist of 2 partsADT consist of 2 parts11 Value DefinitionValue Definition

22 Operator DefinitionOperator Definition

040823040823 1313

Specification of ADTSpecification of ADT

11 Value DefinitionValue DefinitionIt defines the collection of values for the It defines the collection of values for the ADT and consist of two partsADT and consist of two partsa)a) Definition Clause Definition Clause b)b) Condition ClauseCondition Clause eg For ADT RATIONAL eg For ADT RATIONAL Value definition it states that RATIONAL value Value definition it states that RATIONAL value consist of two integers the second of which does not equal consist of two integers the second of which does not equal to zeroto zeroThe keyword The keyword abstract typedefabstract typedef introduce a value definition introduce a value definition

040823040823 1414

Specification of ADTSpecification of ADT

Condition ClauseCondition Clause Used to specify any conditions on the newly defined Used to specify any conditions on the newly defined

typetype The keyword The keyword condition condition is used to specify any is used to specify any

conditions on the newly defined typeconditions on the newly defined typeFor eg for RATIONAL ADTFor eg for RATIONAL ADTCondition Clause denominator may not be zeroCondition Clause denominator may not be zeroNote The definition clause is required but the Note The definition clause is required but the condition clause may not be necessary for every condition clause may not be necessary for every ADTADT

040823040823 1515

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator Definition It defines the operations that are to be It defines the operations that are to be

performed on a data setperformed on a data set Each operator is defined as an abstract Each operator is defined as an abstract

function with three partsfunction with three parts HeaderHeader Optional preconditions Optional preconditions Post conditions Post conditions

040823040823 1616

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator DefinitionFor eg Operator definition for RATIONAL ADTFor eg Operator definition for RATIONAL ADT includes the operations of creation addition includes the operations of creation addition multiplication and equalitymultiplication and equality Now for multiplication operation the operator definition for Now for multiplication operation the operator definition for

RATIONAL ADT isRATIONAL ADT is Abstract RATIONAL mult(ab)helliphellipAbstract RATIONAL mult(ab)helliphellipheaderheader

RATIONAL a b helliphelliphellip RATIONAL a b helliphelliphellip header headermul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip mul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip postcondpostcond

mul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellipmul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellippostcondpostcond

040823040823 1717

Complete example of RATIONL Complete example of RATIONL ADTADT

value definition value definition Abstract typedefAbstract typedeflt int int gtRATIONALlt int int gtRATIONAL ConditionCondition RATIONAL[1]=0 RATIONAL[1]=0 Operator definition Operator definition Abstract equal(ab)Abstract equal(ab) RATIONAL a bRATIONAL a b Postcondition equal==(a[0]b[1]==b[0]b[1])Postcondition equal==(a[0]b[1]==b[0]b[1]) Like this we can declare the other operationsLike this we can declare the other operations

040823040823 1818

Classification of Data StructureClassification of Data Structure

Linear and Non-LinearLinear and Non-Linear

In linear data structure the data items are arranged In linear data structure the data items are arranged in linear sequence eg Array Stack Queue Linked in linear sequence eg Array Stack Queue Linked ListList

In non-linear data items are not in sequence eg In non-linear data items are not in sequence eg Tree graph HeapTree graph Heap

040823040823 1919

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Homogenous and Non-homogenousHomogenous and Non-homogenous

In homogenous data structure all the elements are In homogenous data structure all the elements are of same type eg Arrayof same type eg Array

In non-homogenous data structure the elements In non-homogenous data structure the elements may or may not be of same type eg Recordmay or may not be of same type eg Record

040823040823 2020

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Primitive and Non-PrimitivePrimitive and Non-PrimitivePrimitive data structures constitute thePrimitive data structures constitute thenumber and the characters which are builtnumber and the characters which are builtprograms examples int realspointer programs examples int realspointer datacharaters data logical data datacharaters data logical data

040823040823 2121

What is STACK or Pushdown What is STACK or Pushdown ListList

A ordered collection of items A ordered collection of items into which new items may be into which new items may be inserted and from which items inserted and from which items may be deleted at one end may be deleted at one end called the top of stack called the top of stack

040823040823 2222

Operations on STACKOperations on STACK

PUSHWhen item is added in stackPUSHWhen item is added in stack POPWhen item is removed from POPWhen item is removed from

stackstack EMPTYStack containing no itemsEMPTYStack containing no items StackTopDetermine what the top StackTopDetermine what the top

item on a stack without removing item on a stack without removing itthis is a combination of push amp popitthis is a combination of push amp pop

040823040823 2323

Push amp Pop in STACKPush amp Pop in STACK PUSH OperationPUSH Operation PUSHPUSH(STACK TOPMAXITEM) (STACK TOPMAXITEM) STACK--STACK--Name given to ArrayName given to Array TOP----TOP----It contains the location of top It contains the location of top

elementselements MAX---MAX---It is maximum size of STACKIt is maximum size of STACK ITEM---gtValue that is to be store in stack ITEM---gtValue that is to be store in stack

ifif top = MAX top = MAX thenthen stackfull stackfull top = top+1 top = top+1 stack(top) = item stack(top) = item ReturnReturn

040823040823 2424

Push amp Pop in STACKPush amp Pop in STACK

POP OperationPOP Operation

POPPOP(STACK TOPITEM) (STACK TOPITEM)

ifif top = 0 top = 0 thenthen Underflow Underflow item = stack(top) item = stack(top) top = top-1 top = top-1 Return Return

040823040823 2525

Applications of STACKApplications of STACK

Expression EvaluationExpression EvaluationParenthesis CheckerParenthesis CheckerRecursionRecursion

040823040823 2626

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

Operator preecedenceOperator preecedence^ ---------Higher precedence^ ---------Higher precedence--------Next Precedence--------Next Precedence+_-------Least precedence+_-------Least precedence

040823040823 2727

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

The rules to rememberThe rules to remember

11 Parenthesize the expression Parenthesize the expression starting fro left to rightstarting fro left to right

22 During Parenthesizing the During Parenthesizing the

expression the operands associatedexpression the operands associated

with operator having higher with operator having higher

precedence are first parenthesizedprecedence are first parenthesized

040823040823 2828

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

33 The sub-expression which has been The sub-expression which has been converted into postfix is to be converted into postfix is to be treated as single operandtreated as single operand

44 Once the expression is converted to Once the expression is converted to postfix form remove the postfix form remove the parenthesis parenthesis

Example A+BCExample A+BC A+[(B+C)+(D+E)F]GA+[(B+C)+(D+E)F]G Answer ABC+DE+F+G+Answer ABC+DE+F+G+

040823040823 2929

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

Postfix(QP)Postfix(QP) QmdashgtGiven Infix expressionQmdashgtGiven Infix expression P-gtEquivalent Postfix expressionP-gtEquivalent Postfix expression

11 Push ldquo(ldquo onto STACK and add ldquo)rdquo to the Push ldquo(ldquo onto STACK and add ldquo)rdquo to the end of Qend of Q

22 Scan Q from left to right and repeat step 3 Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK to 6 for each element of Q until the STACK is Emptyis Empty

33 If an operand is encountered add it to PIf an operand is encountered add it to P44 If a left parenthesis is encountered push If a left parenthesis is encountered push

it onto STACK it onto STACK

040823040823 3030

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

55 If an operator reg is encountered If an operator reg is encountered thenthen

(a) ADD reg to STACK(a) ADD reg to STACK

[End of IF][End of IF]

(b) Repeatedly pop from STACK and (b) Repeatedly pop from STACK and add P each operator which has add P each operator which has same precedence as or higher same precedence as or higher precedence than regprecedence than reg

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 13: Data structure

040823040823 1313

Specification of ADTSpecification of ADT

11 Value DefinitionValue DefinitionIt defines the collection of values for the It defines the collection of values for the ADT and consist of two partsADT and consist of two partsa)a) Definition Clause Definition Clause b)b) Condition ClauseCondition Clause eg For ADT RATIONAL eg For ADT RATIONAL Value definition it states that RATIONAL value Value definition it states that RATIONAL value consist of two integers the second of which does not equal consist of two integers the second of which does not equal to zeroto zeroThe keyword The keyword abstract typedefabstract typedef introduce a value definition introduce a value definition

040823040823 1414

Specification of ADTSpecification of ADT

Condition ClauseCondition Clause Used to specify any conditions on the newly defined Used to specify any conditions on the newly defined

typetype The keyword The keyword condition condition is used to specify any is used to specify any

conditions on the newly defined typeconditions on the newly defined typeFor eg for RATIONAL ADTFor eg for RATIONAL ADTCondition Clause denominator may not be zeroCondition Clause denominator may not be zeroNote The definition clause is required but the Note The definition clause is required but the condition clause may not be necessary for every condition clause may not be necessary for every ADTADT

040823040823 1515

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator Definition It defines the operations that are to be It defines the operations that are to be

performed on a data setperformed on a data set Each operator is defined as an abstract Each operator is defined as an abstract

function with three partsfunction with three parts HeaderHeader Optional preconditions Optional preconditions Post conditions Post conditions

040823040823 1616

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator DefinitionFor eg Operator definition for RATIONAL ADTFor eg Operator definition for RATIONAL ADT includes the operations of creation addition includes the operations of creation addition multiplication and equalitymultiplication and equality Now for multiplication operation the operator definition for Now for multiplication operation the operator definition for

RATIONAL ADT isRATIONAL ADT is Abstract RATIONAL mult(ab)helliphellipAbstract RATIONAL mult(ab)helliphellipheaderheader

RATIONAL a b helliphelliphellip RATIONAL a b helliphelliphellip header headermul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip mul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip postcondpostcond

mul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellipmul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellippostcondpostcond

040823040823 1717

Complete example of RATIONL Complete example of RATIONL ADTADT

value definition value definition Abstract typedefAbstract typedeflt int int gtRATIONALlt int int gtRATIONAL ConditionCondition RATIONAL[1]=0 RATIONAL[1]=0 Operator definition Operator definition Abstract equal(ab)Abstract equal(ab) RATIONAL a bRATIONAL a b Postcondition equal==(a[0]b[1]==b[0]b[1])Postcondition equal==(a[0]b[1]==b[0]b[1]) Like this we can declare the other operationsLike this we can declare the other operations

040823040823 1818

Classification of Data StructureClassification of Data Structure

Linear and Non-LinearLinear and Non-Linear

In linear data structure the data items are arranged In linear data structure the data items are arranged in linear sequence eg Array Stack Queue Linked in linear sequence eg Array Stack Queue Linked ListList

In non-linear data items are not in sequence eg In non-linear data items are not in sequence eg Tree graph HeapTree graph Heap

040823040823 1919

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Homogenous and Non-homogenousHomogenous and Non-homogenous

In homogenous data structure all the elements are In homogenous data structure all the elements are of same type eg Arrayof same type eg Array

In non-homogenous data structure the elements In non-homogenous data structure the elements may or may not be of same type eg Recordmay or may not be of same type eg Record

040823040823 2020

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Primitive and Non-PrimitivePrimitive and Non-PrimitivePrimitive data structures constitute thePrimitive data structures constitute thenumber and the characters which are builtnumber and the characters which are builtprograms examples int realspointer programs examples int realspointer datacharaters data logical data datacharaters data logical data

040823040823 2121

What is STACK or Pushdown What is STACK or Pushdown ListList

A ordered collection of items A ordered collection of items into which new items may be into which new items may be inserted and from which items inserted and from which items may be deleted at one end may be deleted at one end called the top of stack called the top of stack

040823040823 2222

Operations on STACKOperations on STACK

PUSHWhen item is added in stackPUSHWhen item is added in stack POPWhen item is removed from POPWhen item is removed from

stackstack EMPTYStack containing no itemsEMPTYStack containing no items StackTopDetermine what the top StackTopDetermine what the top

item on a stack without removing item on a stack without removing itthis is a combination of push amp popitthis is a combination of push amp pop

040823040823 2323

Push amp Pop in STACKPush amp Pop in STACK PUSH OperationPUSH Operation PUSHPUSH(STACK TOPMAXITEM) (STACK TOPMAXITEM) STACK--STACK--Name given to ArrayName given to Array TOP----TOP----It contains the location of top It contains the location of top

elementselements MAX---MAX---It is maximum size of STACKIt is maximum size of STACK ITEM---gtValue that is to be store in stack ITEM---gtValue that is to be store in stack

ifif top = MAX top = MAX thenthen stackfull stackfull top = top+1 top = top+1 stack(top) = item stack(top) = item ReturnReturn

040823040823 2424

Push amp Pop in STACKPush amp Pop in STACK

POP OperationPOP Operation

POPPOP(STACK TOPITEM) (STACK TOPITEM)

ifif top = 0 top = 0 thenthen Underflow Underflow item = stack(top) item = stack(top) top = top-1 top = top-1 Return Return

040823040823 2525

Applications of STACKApplications of STACK

Expression EvaluationExpression EvaluationParenthesis CheckerParenthesis CheckerRecursionRecursion

040823040823 2626

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

Operator preecedenceOperator preecedence^ ---------Higher precedence^ ---------Higher precedence--------Next Precedence--------Next Precedence+_-------Least precedence+_-------Least precedence

040823040823 2727

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

The rules to rememberThe rules to remember

11 Parenthesize the expression Parenthesize the expression starting fro left to rightstarting fro left to right

22 During Parenthesizing the During Parenthesizing the

expression the operands associatedexpression the operands associated

with operator having higher with operator having higher

precedence are first parenthesizedprecedence are first parenthesized

040823040823 2828

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

33 The sub-expression which has been The sub-expression which has been converted into postfix is to be converted into postfix is to be treated as single operandtreated as single operand

44 Once the expression is converted to Once the expression is converted to postfix form remove the postfix form remove the parenthesis parenthesis

Example A+BCExample A+BC A+[(B+C)+(D+E)F]GA+[(B+C)+(D+E)F]G Answer ABC+DE+F+G+Answer ABC+DE+F+G+

040823040823 2929

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

Postfix(QP)Postfix(QP) QmdashgtGiven Infix expressionQmdashgtGiven Infix expression P-gtEquivalent Postfix expressionP-gtEquivalent Postfix expression

11 Push ldquo(ldquo onto STACK and add ldquo)rdquo to the Push ldquo(ldquo onto STACK and add ldquo)rdquo to the end of Qend of Q

22 Scan Q from left to right and repeat step 3 Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK to 6 for each element of Q until the STACK is Emptyis Empty

33 If an operand is encountered add it to PIf an operand is encountered add it to P44 If a left parenthesis is encountered push If a left parenthesis is encountered push

it onto STACK it onto STACK

040823040823 3030

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

55 If an operator reg is encountered If an operator reg is encountered thenthen

(a) ADD reg to STACK(a) ADD reg to STACK

[End of IF][End of IF]

(b) Repeatedly pop from STACK and (b) Repeatedly pop from STACK and add P each operator which has add P each operator which has same precedence as or higher same precedence as or higher precedence than regprecedence than reg

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 14: Data structure

040823040823 1414

Specification of ADTSpecification of ADT

Condition ClauseCondition Clause Used to specify any conditions on the newly defined Used to specify any conditions on the newly defined

typetype The keyword The keyword condition condition is used to specify any is used to specify any

conditions on the newly defined typeconditions on the newly defined typeFor eg for RATIONAL ADTFor eg for RATIONAL ADTCondition Clause denominator may not be zeroCondition Clause denominator may not be zeroNote The definition clause is required but the Note The definition clause is required but the condition clause may not be necessary for every condition clause may not be necessary for every ADTADT

040823040823 1515

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator Definition It defines the operations that are to be It defines the operations that are to be

performed on a data setperformed on a data set Each operator is defined as an abstract Each operator is defined as an abstract

function with three partsfunction with three parts HeaderHeader Optional preconditions Optional preconditions Post conditions Post conditions

040823040823 1616

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator DefinitionFor eg Operator definition for RATIONAL ADTFor eg Operator definition for RATIONAL ADT includes the operations of creation addition includes the operations of creation addition multiplication and equalitymultiplication and equality Now for multiplication operation the operator definition for Now for multiplication operation the operator definition for

RATIONAL ADT isRATIONAL ADT is Abstract RATIONAL mult(ab)helliphellipAbstract RATIONAL mult(ab)helliphellipheaderheader

RATIONAL a b helliphelliphellip RATIONAL a b helliphelliphellip header headermul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip mul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip postcondpostcond

mul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellipmul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellippostcondpostcond

040823040823 1717

Complete example of RATIONL Complete example of RATIONL ADTADT

value definition value definition Abstract typedefAbstract typedeflt int int gtRATIONALlt int int gtRATIONAL ConditionCondition RATIONAL[1]=0 RATIONAL[1]=0 Operator definition Operator definition Abstract equal(ab)Abstract equal(ab) RATIONAL a bRATIONAL a b Postcondition equal==(a[0]b[1]==b[0]b[1])Postcondition equal==(a[0]b[1]==b[0]b[1]) Like this we can declare the other operationsLike this we can declare the other operations

040823040823 1818

Classification of Data StructureClassification of Data Structure

Linear and Non-LinearLinear and Non-Linear

In linear data structure the data items are arranged In linear data structure the data items are arranged in linear sequence eg Array Stack Queue Linked in linear sequence eg Array Stack Queue Linked ListList

In non-linear data items are not in sequence eg In non-linear data items are not in sequence eg Tree graph HeapTree graph Heap

040823040823 1919

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Homogenous and Non-homogenousHomogenous and Non-homogenous

In homogenous data structure all the elements are In homogenous data structure all the elements are of same type eg Arrayof same type eg Array

In non-homogenous data structure the elements In non-homogenous data structure the elements may or may not be of same type eg Recordmay or may not be of same type eg Record

040823040823 2020

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Primitive and Non-PrimitivePrimitive and Non-PrimitivePrimitive data structures constitute thePrimitive data structures constitute thenumber and the characters which are builtnumber and the characters which are builtprograms examples int realspointer programs examples int realspointer datacharaters data logical data datacharaters data logical data

040823040823 2121

What is STACK or Pushdown What is STACK or Pushdown ListList

A ordered collection of items A ordered collection of items into which new items may be into which new items may be inserted and from which items inserted and from which items may be deleted at one end may be deleted at one end called the top of stack called the top of stack

040823040823 2222

Operations on STACKOperations on STACK

PUSHWhen item is added in stackPUSHWhen item is added in stack POPWhen item is removed from POPWhen item is removed from

stackstack EMPTYStack containing no itemsEMPTYStack containing no items StackTopDetermine what the top StackTopDetermine what the top

item on a stack without removing item on a stack without removing itthis is a combination of push amp popitthis is a combination of push amp pop

040823040823 2323

Push amp Pop in STACKPush amp Pop in STACK PUSH OperationPUSH Operation PUSHPUSH(STACK TOPMAXITEM) (STACK TOPMAXITEM) STACK--STACK--Name given to ArrayName given to Array TOP----TOP----It contains the location of top It contains the location of top

elementselements MAX---MAX---It is maximum size of STACKIt is maximum size of STACK ITEM---gtValue that is to be store in stack ITEM---gtValue that is to be store in stack

ifif top = MAX top = MAX thenthen stackfull stackfull top = top+1 top = top+1 stack(top) = item stack(top) = item ReturnReturn

040823040823 2424

Push amp Pop in STACKPush amp Pop in STACK

POP OperationPOP Operation

POPPOP(STACK TOPITEM) (STACK TOPITEM)

ifif top = 0 top = 0 thenthen Underflow Underflow item = stack(top) item = stack(top) top = top-1 top = top-1 Return Return

040823040823 2525

Applications of STACKApplications of STACK

Expression EvaluationExpression EvaluationParenthesis CheckerParenthesis CheckerRecursionRecursion

040823040823 2626

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

Operator preecedenceOperator preecedence^ ---------Higher precedence^ ---------Higher precedence--------Next Precedence--------Next Precedence+_-------Least precedence+_-------Least precedence

040823040823 2727

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

The rules to rememberThe rules to remember

11 Parenthesize the expression Parenthesize the expression starting fro left to rightstarting fro left to right

22 During Parenthesizing the During Parenthesizing the

expression the operands associatedexpression the operands associated

with operator having higher with operator having higher

precedence are first parenthesizedprecedence are first parenthesized

040823040823 2828

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

33 The sub-expression which has been The sub-expression which has been converted into postfix is to be converted into postfix is to be treated as single operandtreated as single operand

44 Once the expression is converted to Once the expression is converted to postfix form remove the postfix form remove the parenthesis parenthesis

Example A+BCExample A+BC A+[(B+C)+(D+E)F]GA+[(B+C)+(D+E)F]G Answer ABC+DE+F+G+Answer ABC+DE+F+G+

040823040823 2929

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

Postfix(QP)Postfix(QP) QmdashgtGiven Infix expressionQmdashgtGiven Infix expression P-gtEquivalent Postfix expressionP-gtEquivalent Postfix expression

11 Push ldquo(ldquo onto STACK and add ldquo)rdquo to the Push ldquo(ldquo onto STACK and add ldquo)rdquo to the end of Qend of Q

22 Scan Q from left to right and repeat step 3 Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK to 6 for each element of Q until the STACK is Emptyis Empty

33 If an operand is encountered add it to PIf an operand is encountered add it to P44 If a left parenthesis is encountered push If a left parenthesis is encountered push

it onto STACK it onto STACK

040823040823 3030

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

55 If an operator reg is encountered If an operator reg is encountered thenthen

(a) ADD reg to STACK(a) ADD reg to STACK

[End of IF][End of IF]

(b) Repeatedly pop from STACK and (b) Repeatedly pop from STACK and add P each operator which has add P each operator which has same precedence as or higher same precedence as or higher precedence than regprecedence than reg

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 15: Data structure

040823040823 1515

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator Definition It defines the operations that are to be It defines the operations that are to be

performed on a data setperformed on a data set Each operator is defined as an abstract Each operator is defined as an abstract

function with three partsfunction with three parts HeaderHeader Optional preconditions Optional preconditions Post conditions Post conditions

040823040823 1616

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator DefinitionFor eg Operator definition for RATIONAL ADTFor eg Operator definition for RATIONAL ADT includes the operations of creation addition includes the operations of creation addition multiplication and equalitymultiplication and equality Now for multiplication operation the operator definition for Now for multiplication operation the operator definition for

RATIONAL ADT isRATIONAL ADT is Abstract RATIONAL mult(ab)helliphellipAbstract RATIONAL mult(ab)helliphellipheaderheader

RATIONAL a b helliphelliphellip RATIONAL a b helliphelliphellip header headermul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip mul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip postcondpostcond

mul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellipmul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellippostcondpostcond

040823040823 1717

Complete example of RATIONL Complete example of RATIONL ADTADT

value definition value definition Abstract typedefAbstract typedeflt int int gtRATIONALlt int int gtRATIONAL ConditionCondition RATIONAL[1]=0 RATIONAL[1]=0 Operator definition Operator definition Abstract equal(ab)Abstract equal(ab) RATIONAL a bRATIONAL a b Postcondition equal==(a[0]b[1]==b[0]b[1])Postcondition equal==(a[0]b[1]==b[0]b[1]) Like this we can declare the other operationsLike this we can declare the other operations

040823040823 1818

Classification of Data StructureClassification of Data Structure

Linear and Non-LinearLinear and Non-Linear

In linear data structure the data items are arranged In linear data structure the data items are arranged in linear sequence eg Array Stack Queue Linked in linear sequence eg Array Stack Queue Linked ListList

In non-linear data items are not in sequence eg In non-linear data items are not in sequence eg Tree graph HeapTree graph Heap

040823040823 1919

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Homogenous and Non-homogenousHomogenous and Non-homogenous

In homogenous data structure all the elements are In homogenous data structure all the elements are of same type eg Arrayof same type eg Array

In non-homogenous data structure the elements In non-homogenous data structure the elements may or may not be of same type eg Recordmay or may not be of same type eg Record

040823040823 2020

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Primitive and Non-PrimitivePrimitive and Non-PrimitivePrimitive data structures constitute thePrimitive data structures constitute thenumber and the characters which are builtnumber and the characters which are builtprograms examples int realspointer programs examples int realspointer datacharaters data logical data datacharaters data logical data

040823040823 2121

What is STACK or Pushdown What is STACK or Pushdown ListList

A ordered collection of items A ordered collection of items into which new items may be into which new items may be inserted and from which items inserted and from which items may be deleted at one end may be deleted at one end called the top of stack called the top of stack

040823040823 2222

Operations on STACKOperations on STACK

PUSHWhen item is added in stackPUSHWhen item is added in stack POPWhen item is removed from POPWhen item is removed from

stackstack EMPTYStack containing no itemsEMPTYStack containing no items StackTopDetermine what the top StackTopDetermine what the top

item on a stack without removing item on a stack without removing itthis is a combination of push amp popitthis is a combination of push amp pop

040823040823 2323

Push amp Pop in STACKPush amp Pop in STACK PUSH OperationPUSH Operation PUSHPUSH(STACK TOPMAXITEM) (STACK TOPMAXITEM) STACK--STACK--Name given to ArrayName given to Array TOP----TOP----It contains the location of top It contains the location of top

elementselements MAX---MAX---It is maximum size of STACKIt is maximum size of STACK ITEM---gtValue that is to be store in stack ITEM---gtValue that is to be store in stack

ifif top = MAX top = MAX thenthen stackfull stackfull top = top+1 top = top+1 stack(top) = item stack(top) = item ReturnReturn

040823040823 2424

Push amp Pop in STACKPush amp Pop in STACK

POP OperationPOP Operation

POPPOP(STACK TOPITEM) (STACK TOPITEM)

ifif top = 0 top = 0 thenthen Underflow Underflow item = stack(top) item = stack(top) top = top-1 top = top-1 Return Return

040823040823 2525

Applications of STACKApplications of STACK

Expression EvaluationExpression EvaluationParenthesis CheckerParenthesis CheckerRecursionRecursion

040823040823 2626

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

Operator preecedenceOperator preecedence^ ---------Higher precedence^ ---------Higher precedence--------Next Precedence--------Next Precedence+_-------Least precedence+_-------Least precedence

040823040823 2727

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

The rules to rememberThe rules to remember

11 Parenthesize the expression Parenthesize the expression starting fro left to rightstarting fro left to right

22 During Parenthesizing the During Parenthesizing the

expression the operands associatedexpression the operands associated

with operator having higher with operator having higher

precedence are first parenthesizedprecedence are first parenthesized

040823040823 2828

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

33 The sub-expression which has been The sub-expression which has been converted into postfix is to be converted into postfix is to be treated as single operandtreated as single operand

44 Once the expression is converted to Once the expression is converted to postfix form remove the postfix form remove the parenthesis parenthesis

Example A+BCExample A+BC A+[(B+C)+(D+E)F]GA+[(B+C)+(D+E)F]G Answer ABC+DE+F+G+Answer ABC+DE+F+G+

040823040823 2929

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

Postfix(QP)Postfix(QP) QmdashgtGiven Infix expressionQmdashgtGiven Infix expression P-gtEquivalent Postfix expressionP-gtEquivalent Postfix expression

11 Push ldquo(ldquo onto STACK and add ldquo)rdquo to the Push ldquo(ldquo onto STACK and add ldquo)rdquo to the end of Qend of Q

22 Scan Q from left to right and repeat step 3 Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK to 6 for each element of Q until the STACK is Emptyis Empty

33 If an operand is encountered add it to PIf an operand is encountered add it to P44 If a left parenthesis is encountered push If a left parenthesis is encountered push

it onto STACK it onto STACK

040823040823 3030

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

55 If an operator reg is encountered If an operator reg is encountered thenthen

(a) ADD reg to STACK(a) ADD reg to STACK

[End of IF][End of IF]

(b) Repeatedly pop from STACK and (b) Repeatedly pop from STACK and add P each operator which has add P each operator which has same precedence as or higher same precedence as or higher precedence than regprecedence than reg

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 16: Data structure

040823040823 1616

Specification of ADTSpecification of ADT

22 Operator DefinitionOperator DefinitionFor eg Operator definition for RATIONAL ADTFor eg Operator definition for RATIONAL ADT includes the operations of creation addition includes the operations of creation addition multiplication and equalitymultiplication and equality Now for multiplication operation the operator definition for Now for multiplication operation the operator definition for

RATIONAL ADT isRATIONAL ADT is Abstract RATIONAL mult(ab)helliphellipAbstract RATIONAL mult(ab)helliphellipheaderheader

RATIONAL a b helliphelliphellip RATIONAL a b helliphelliphellip header headermul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip mul[0]=a[0]b[0] helliphelliphelliphelliphelliphelliphellip postcondpostcond

mul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellipmul[1]=a[1]b[1]helliphelliphelliphelliphelliphelliphelliphellippostcondpostcond

040823040823 1717

Complete example of RATIONL Complete example of RATIONL ADTADT

value definition value definition Abstract typedefAbstract typedeflt int int gtRATIONALlt int int gtRATIONAL ConditionCondition RATIONAL[1]=0 RATIONAL[1]=0 Operator definition Operator definition Abstract equal(ab)Abstract equal(ab) RATIONAL a bRATIONAL a b Postcondition equal==(a[0]b[1]==b[0]b[1])Postcondition equal==(a[0]b[1]==b[0]b[1]) Like this we can declare the other operationsLike this we can declare the other operations

040823040823 1818

Classification of Data StructureClassification of Data Structure

Linear and Non-LinearLinear and Non-Linear

In linear data structure the data items are arranged In linear data structure the data items are arranged in linear sequence eg Array Stack Queue Linked in linear sequence eg Array Stack Queue Linked ListList

In non-linear data items are not in sequence eg In non-linear data items are not in sequence eg Tree graph HeapTree graph Heap

040823040823 1919

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Homogenous and Non-homogenousHomogenous and Non-homogenous

In homogenous data structure all the elements are In homogenous data structure all the elements are of same type eg Arrayof same type eg Array

In non-homogenous data structure the elements In non-homogenous data structure the elements may or may not be of same type eg Recordmay or may not be of same type eg Record

040823040823 2020

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Primitive and Non-PrimitivePrimitive and Non-PrimitivePrimitive data structures constitute thePrimitive data structures constitute thenumber and the characters which are builtnumber and the characters which are builtprograms examples int realspointer programs examples int realspointer datacharaters data logical data datacharaters data logical data

040823040823 2121

What is STACK or Pushdown What is STACK or Pushdown ListList

A ordered collection of items A ordered collection of items into which new items may be into which new items may be inserted and from which items inserted and from which items may be deleted at one end may be deleted at one end called the top of stack called the top of stack

040823040823 2222

Operations on STACKOperations on STACK

PUSHWhen item is added in stackPUSHWhen item is added in stack POPWhen item is removed from POPWhen item is removed from

stackstack EMPTYStack containing no itemsEMPTYStack containing no items StackTopDetermine what the top StackTopDetermine what the top

item on a stack without removing item on a stack without removing itthis is a combination of push amp popitthis is a combination of push amp pop

040823040823 2323

Push amp Pop in STACKPush amp Pop in STACK PUSH OperationPUSH Operation PUSHPUSH(STACK TOPMAXITEM) (STACK TOPMAXITEM) STACK--STACK--Name given to ArrayName given to Array TOP----TOP----It contains the location of top It contains the location of top

elementselements MAX---MAX---It is maximum size of STACKIt is maximum size of STACK ITEM---gtValue that is to be store in stack ITEM---gtValue that is to be store in stack

ifif top = MAX top = MAX thenthen stackfull stackfull top = top+1 top = top+1 stack(top) = item stack(top) = item ReturnReturn

040823040823 2424

Push amp Pop in STACKPush amp Pop in STACK

POP OperationPOP Operation

POPPOP(STACK TOPITEM) (STACK TOPITEM)

ifif top = 0 top = 0 thenthen Underflow Underflow item = stack(top) item = stack(top) top = top-1 top = top-1 Return Return

040823040823 2525

Applications of STACKApplications of STACK

Expression EvaluationExpression EvaluationParenthesis CheckerParenthesis CheckerRecursionRecursion

040823040823 2626

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

Operator preecedenceOperator preecedence^ ---------Higher precedence^ ---------Higher precedence--------Next Precedence--------Next Precedence+_-------Least precedence+_-------Least precedence

040823040823 2727

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

The rules to rememberThe rules to remember

11 Parenthesize the expression Parenthesize the expression starting fro left to rightstarting fro left to right

22 During Parenthesizing the During Parenthesizing the

expression the operands associatedexpression the operands associated

with operator having higher with operator having higher

precedence are first parenthesizedprecedence are first parenthesized

040823040823 2828

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

33 The sub-expression which has been The sub-expression which has been converted into postfix is to be converted into postfix is to be treated as single operandtreated as single operand

44 Once the expression is converted to Once the expression is converted to postfix form remove the postfix form remove the parenthesis parenthesis

Example A+BCExample A+BC A+[(B+C)+(D+E)F]GA+[(B+C)+(D+E)F]G Answer ABC+DE+F+G+Answer ABC+DE+F+G+

040823040823 2929

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

Postfix(QP)Postfix(QP) QmdashgtGiven Infix expressionQmdashgtGiven Infix expression P-gtEquivalent Postfix expressionP-gtEquivalent Postfix expression

11 Push ldquo(ldquo onto STACK and add ldquo)rdquo to the Push ldquo(ldquo onto STACK and add ldquo)rdquo to the end of Qend of Q

22 Scan Q from left to right and repeat step 3 Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK to 6 for each element of Q until the STACK is Emptyis Empty

33 If an operand is encountered add it to PIf an operand is encountered add it to P44 If a left parenthesis is encountered push If a left parenthesis is encountered push

it onto STACK it onto STACK

040823040823 3030

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

55 If an operator reg is encountered If an operator reg is encountered thenthen

(a) ADD reg to STACK(a) ADD reg to STACK

[End of IF][End of IF]

(b) Repeatedly pop from STACK and (b) Repeatedly pop from STACK and add P each operator which has add P each operator which has same precedence as or higher same precedence as or higher precedence than regprecedence than reg

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 17: Data structure

040823040823 1717

Complete example of RATIONL Complete example of RATIONL ADTADT

value definition value definition Abstract typedefAbstract typedeflt int int gtRATIONALlt int int gtRATIONAL ConditionCondition RATIONAL[1]=0 RATIONAL[1]=0 Operator definition Operator definition Abstract equal(ab)Abstract equal(ab) RATIONAL a bRATIONAL a b Postcondition equal==(a[0]b[1]==b[0]b[1])Postcondition equal==(a[0]b[1]==b[0]b[1]) Like this we can declare the other operationsLike this we can declare the other operations

040823040823 1818

Classification of Data StructureClassification of Data Structure

Linear and Non-LinearLinear and Non-Linear

In linear data structure the data items are arranged In linear data structure the data items are arranged in linear sequence eg Array Stack Queue Linked in linear sequence eg Array Stack Queue Linked ListList

In non-linear data items are not in sequence eg In non-linear data items are not in sequence eg Tree graph HeapTree graph Heap

040823040823 1919

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Homogenous and Non-homogenousHomogenous and Non-homogenous

In homogenous data structure all the elements are In homogenous data structure all the elements are of same type eg Arrayof same type eg Array

In non-homogenous data structure the elements In non-homogenous data structure the elements may or may not be of same type eg Recordmay or may not be of same type eg Record

040823040823 2020

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Primitive and Non-PrimitivePrimitive and Non-PrimitivePrimitive data structures constitute thePrimitive data structures constitute thenumber and the characters which are builtnumber and the characters which are builtprograms examples int realspointer programs examples int realspointer datacharaters data logical data datacharaters data logical data

040823040823 2121

What is STACK or Pushdown What is STACK or Pushdown ListList

A ordered collection of items A ordered collection of items into which new items may be into which new items may be inserted and from which items inserted and from which items may be deleted at one end may be deleted at one end called the top of stack called the top of stack

040823040823 2222

Operations on STACKOperations on STACK

PUSHWhen item is added in stackPUSHWhen item is added in stack POPWhen item is removed from POPWhen item is removed from

stackstack EMPTYStack containing no itemsEMPTYStack containing no items StackTopDetermine what the top StackTopDetermine what the top

item on a stack without removing item on a stack without removing itthis is a combination of push amp popitthis is a combination of push amp pop

040823040823 2323

Push amp Pop in STACKPush amp Pop in STACK PUSH OperationPUSH Operation PUSHPUSH(STACK TOPMAXITEM) (STACK TOPMAXITEM) STACK--STACK--Name given to ArrayName given to Array TOP----TOP----It contains the location of top It contains the location of top

elementselements MAX---MAX---It is maximum size of STACKIt is maximum size of STACK ITEM---gtValue that is to be store in stack ITEM---gtValue that is to be store in stack

ifif top = MAX top = MAX thenthen stackfull stackfull top = top+1 top = top+1 stack(top) = item stack(top) = item ReturnReturn

040823040823 2424

Push amp Pop in STACKPush amp Pop in STACK

POP OperationPOP Operation

POPPOP(STACK TOPITEM) (STACK TOPITEM)

ifif top = 0 top = 0 thenthen Underflow Underflow item = stack(top) item = stack(top) top = top-1 top = top-1 Return Return

040823040823 2525

Applications of STACKApplications of STACK

Expression EvaluationExpression EvaluationParenthesis CheckerParenthesis CheckerRecursionRecursion

040823040823 2626

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

Operator preecedenceOperator preecedence^ ---------Higher precedence^ ---------Higher precedence--------Next Precedence--------Next Precedence+_-------Least precedence+_-------Least precedence

040823040823 2727

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

The rules to rememberThe rules to remember

11 Parenthesize the expression Parenthesize the expression starting fro left to rightstarting fro left to right

22 During Parenthesizing the During Parenthesizing the

expression the operands associatedexpression the operands associated

with operator having higher with operator having higher

precedence are first parenthesizedprecedence are first parenthesized

040823040823 2828

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

33 The sub-expression which has been The sub-expression which has been converted into postfix is to be converted into postfix is to be treated as single operandtreated as single operand

44 Once the expression is converted to Once the expression is converted to postfix form remove the postfix form remove the parenthesis parenthesis

Example A+BCExample A+BC A+[(B+C)+(D+E)F]GA+[(B+C)+(D+E)F]G Answer ABC+DE+F+G+Answer ABC+DE+F+G+

040823040823 2929

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

Postfix(QP)Postfix(QP) QmdashgtGiven Infix expressionQmdashgtGiven Infix expression P-gtEquivalent Postfix expressionP-gtEquivalent Postfix expression

11 Push ldquo(ldquo onto STACK and add ldquo)rdquo to the Push ldquo(ldquo onto STACK and add ldquo)rdquo to the end of Qend of Q

22 Scan Q from left to right and repeat step 3 Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK to 6 for each element of Q until the STACK is Emptyis Empty

33 If an operand is encountered add it to PIf an operand is encountered add it to P44 If a left parenthesis is encountered push If a left parenthesis is encountered push

it onto STACK it onto STACK

040823040823 3030

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

55 If an operator reg is encountered If an operator reg is encountered thenthen

(a) ADD reg to STACK(a) ADD reg to STACK

[End of IF][End of IF]

(b) Repeatedly pop from STACK and (b) Repeatedly pop from STACK and add P each operator which has add P each operator which has same precedence as or higher same precedence as or higher precedence than regprecedence than reg

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 18: Data structure

040823040823 1818

Classification of Data StructureClassification of Data Structure

Linear and Non-LinearLinear and Non-Linear

In linear data structure the data items are arranged In linear data structure the data items are arranged in linear sequence eg Array Stack Queue Linked in linear sequence eg Array Stack Queue Linked ListList

In non-linear data items are not in sequence eg In non-linear data items are not in sequence eg Tree graph HeapTree graph Heap

040823040823 1919

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Homogenous and Non-homogenousHomogenous and Non-homogenous

In homogenous data structure all the elements are In homogenous data structure all the elements are of same type eg Arrayof same type eg Array

In non-homogenous data structure the elements In non-homogenous data structure the elements may or may not be of same type eg Recordmay or may not be of same type eg Record

040823040823 2020

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Primitive and Non-PrimitivePrimitive and Non-PrimitivePrimitive data structures constitute thePrimitive data structures constitute thenumber and the characters which are builtnumber and the characters which are builtprograms examples int realspointer programs examples int realspointer datacharaters data logical data datacharaters data logical data

040823040823 2121

What is STACK or Pushdown What is STACK or Pushdown ListList

A ordered collection of items A ordered collection of items into which new items may be into which new items may be inserted and from which items inserted and from which items may be deleted at one end may be deleted at one end called the top of stack called the top of stack

040823040823 2222

Operations on STACKOperations on STACK

PUSHWhen item is added in stackPUSHWhen item is added in stack POPWhen item is removed from POPWhen item is removed from

stackstack EMPTYStack containing no itemsEMPTYStack containing no items StackTopDetermine what the top StackTopDetermine what the top

item on a stack without removing item on a stack without removing itthis is a combination of push amp popitthis is a combination of push amp pop

040823040823 2323

Push amp Pop in STACKPush amp Pop in STACK PUSH OperationPUSH Operation PUSHPUSH(STACK TOPMAXITEM) (STACK TOPMAXITEM) STACK--STACK--Name given to ArrayName given to Array TOP----TOP----It contains the location of top It contains the location of top

elementselements MAX---MAX---It is maximum size of STACKIt is maximum size of STACK ITEM---gtValue that is to be store in stack ITEM---gtValue that is to be store in stack

ifif top = MAX top = MAX thenthen stackfull stackfull top = top+1 top = top+1 stack(top) = item stack(top) = item ReturnReturn

040823040823 2424

Push amp Pop in STACKPush amp Pop in STACK

POP OperationPOP Operation

POPPOP(STACK TOPITEM) (STACK TOPITEM)

ifif top = 0 top = 0 thenthen Underflow Underflow item = stack(top) item = stack(top) top = top-1 top = top-1 Return Return

040823040823 2525

Applications of STACKApplications of STACK

Expression EvaluationExpression EvaluationParenthesis CheckerParenthesis CheckerRecursionRecursion

040823040823 2626

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

Operator preecedenceOperator preecedence^ ---------Higher precedence^ ---------Higher precedence--------Next Precedence--------Next Precedence+_-------Least precedence+_-------Least precedence

040823040823 2727

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

The rules to rememberThe rules to remember

11 Parenthesize the expression Parenthesize the expression starting fro left to rightstarting fro left to right

22 During Parenthesizing the During Parenthesizing the

expression the operands associatedexpression the operands associated

with operator having higher with operator having higher

precedence are first parenthesizedprecedence are first parenthesized

040823040823 2828

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

33 The sub-expression which has been The sub-expression which has been converted into postfix is to be converted into postfix is to be treated as single operandtreated as single operand

44 Once the expression is converted to Once the expression is converted to postfix form remove the postfix form remove the parenthesis parenthesis

Example A+BCExample A+BC A+[(B+C)+(D+E)F]GA+[(B+C)+(D+E)F]G Answer ABC+DE+F+G+Answer ABC+DE+F+G+

040823040823 2929

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

Postfix(QP)Postfix(QP) QmdashgtGiven Infix expressionQmdashgtGiven Infix expression P-gtEquivalent Postfix expressionP-gtEquivalent Postfix expression

11 Push ldquo(ldquo onto STACK and add ldquo)rdquo to the Push ldquo(ldquo onto STACK and add ldquo)rdquo to the end of Qend of Q

22 Scan Q from left to right and repeat step 3 Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK to 6 for each element of Q until the STACK is Emptyis Empty

33 If an operand is encountered add it to PIf an operand is encountered add it to P44 If a left parenthesis is encountered push If a left parenthesis is encountered push

it onto STACK it onto STACK

040823040823 3030

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

55 If an operator reg is encountered If an operator reg is encountered thenthen

(a) ADD reg to STACK(a) ADD reg to STACK

[End of IF][End of IF]

(b) Repeatedly pop from STACK and (b) Repeatedly pop from STACK and add P each operator which has add P each operator which has same precedence as or higher same precedence as or higher precedence than regprecedence than reg

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 19: Data structure

040823040823 1919

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Homogenous and Non-homogenousHomogenous and Non-homogenous

In homogenous data structure all the elements are In homogenous data structure all the elements are of same type eg Arrayof same type eg Array

In non-homogenous data structure the elements In non-homogenous data structure the elements may or may not be of same type eg Recordmay or may not be of same type eg Record

040823040823 2020

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Primitive and Non-PrimitivePrimitive and Non-PrimitivePrimitive data structures constitute thePrimitive data structures constitute thenumber and the characters which are builtnumber and the characters which are builtprograms examples int realspointer programs examples int realspointer datacharaters data logical data datacharaters data logical data

040823040823 2121

What is STACK or Pushdown What is STACK or Pushdown ListList

A ordered collection of items A ordered collection of items into which new items may be into which new items may be inserted and from which items inserted and from which items may be deleted at one end may be deleted at one end called the top of stack called the top of stack

040823040823 2222

Operations on STACKOperations on STACK

PUSHWhen item is added in stackPUSHWhen item is added in stack POPWhen item is removed from POPWhen item is removed from

stackstack EMPTYStack containing no itemsEMPTYStack containing no items StackTopDetermine what the top StackTopDetermine what the top

item on a stack without removing item on a stack without removing itthis is a combination of push amp popitthis is a combination of push amp pop

040823040823 2323

Push amp Pop in STACKPush amp Pop in STACK PUSH OperationPUSH Operation PUSHPUSH(STACK TOPMAXITEM) (STACK TOPMAXITEM) STACK--STACK--Name given to ArrayName given to Array TOP----TOP----It contains the location of top It contains the location of top

elementselements MAX---MAX---It is maximum size of STACKIt is maximum size of STACK ITEM---gtValue that is to be store in stack ITEM---gtValue that is to be store in stack

ifif top = MAX top = MAX thenthen stackfull stackfull top = top+1 top = top+1 stack(top) = item stack(top) = item ReturnReturn

040823040823 2424

Push amp Pop in STACKPush amp Pop in STACK

POP OperationPOP Operation

POPPOP(STACK TOPITEM) (STACK TOPITEM)

ifif top = 0 top = 0 thenthen Underflow Underflow item = stack(top) item = stack(top) top = top-1 top = top-1 Return Return

040823040823 2525

Applications of STACKApplications of STACK

Expression EvaluationExpression EvaluationParenthesis CheckerParenthesis CheckerRecursionRecursion

040823040823 2626

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

Operator preecedenceOperator preecedence^ ---------Higher precedence^ ---------Higher precedence--------Next Precedence--------Next Precedence+_-------Least precedence+_-------Least precedence

040823040823 2727

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

The rules to rememberThe rules to remember

11 Parenthesize the expression Parenthesize the expression starting fro left to rightstarting fro left to right

22 During Parenthesizing the During Parenthesizing the

expression the operands associatedexpression the operands associated

with operator having higher with operator having higher

precedence are first parenthesizedprecedence are first parenthesized

040823040823 2828

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

33 The sub-expression which has been The sub-expression which has been converted into postfix is to be converted into postfix is to be treated as single operandtreated as single operand

44 Once the expression is converted to Once the expression is converted to postfix form remove the postfix form remove the parenthesis parenthesis

Example A+BCExample A+BC A+[(B+C)+(D+E)F]GA+[(B+C)+(D+E)F]G Answer ABC+DE+F+G+Answer ABC+DE+F+G+

040823040823 2929

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

Postfix(QP)Postfix(QP) QmdashgtGiven Infix expressionQmdashgtGiven Infix expression P-gtEquivalent Postfix expressionP-gtEquivalent Postfix expression

11 Push ldquo(ldquo onto STACK and add ldquo)rdquo to the Push ldquo(ldquo onto STACK and add ldquo)rdquo to the end of Qend of Q

22 Scan Q from left to right and repeat step 3 Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK to 6 for each element of Q until the STACK is Emptyis Empty

33 If an operand is encountered add it to PIf an operand is encountered add it to P44 If a left parenthesis is encountered push If a left parenthesis is encountered push

it onto STACK it onto STACK

040823040823 3030

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

55 If an operator reg is encountered If an operator reg is encountered thenthen

(a) ADD reg to STACK(a) ADD reg to STACK

[End of IF][End of IF]

(b) Repeatedly pop from STACK and (b) Repeatedly pop from STACK and add P each operator which has add P each operator which has same precedence as or higher same precedence as or higher precedence than regprecedence than reg

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 20: Data structure

040823040823 2020

Classification of Data Structure Classification of Data Structure (Continue)(Continue)

Primitive and Non-PrimitivePrimitive and Non-PrimitivePrimitive data structures constitute thePrimitive data structures constitute thenumber and the characters which are builtnumber and the characters which are builtprograms examples int realspointer programs examples int realspointer datacharaters data logical data datacharaters data logical data

040823040823 2121

What is STACK or Pushdown What is STACK or Pushdown ListList

A ordered collection of items A ordered collection of items into which new items may be into which new items may be inserted and from which items inserted and from which items may be deleted at one end may be deleted at one end called the top of stack called the top of stack

040823040823 2222

Operations on STACKOperations on STACK

PUSHWhen item is added in stackPUSHWhen item is added in stack POPWhen item is removed from POPWhen item is removed from

stackstack EMPTYStack containing no itemsEMPTYStack containing no items StackTopDetermine what the top StackTopDetermine what the top

item on a stack without removing item on a stack without removing itthis is a combination of push amp popitthis is a combination of push amp pop

040823040823 2323

Push amp Pop in STACKPush amp Pop in STACK PUSH OperationPUSH Operation PUSHPUSH(STACK TOPMAXITEM) (STACK TOPMAXITEM) STACK--STACK--Name given to ArrayName given to Array TOP----TOP----It contains the location of top It contains the location of top

elementselements MAX---MAX---It is maximum size of STACKIt is maximum size of STACK ITEM---gtValue that is to be store in stack ITEM---gtValue that is to be store in stack

ifif top = MAX top = MAX thenthen stackfull stackfull top = top+1 top = top+1 stack(top) = item stack(top) = item ReturnReturn

040823040823 2424

Push amp Pop in STACKPush amp Pop in STACK

POP OperationPOP Operation

POPPOP(STACK TOPITEM) (STACK TOPITEM)

ifif top = 0 top = 0 thenthen Underflow Underflow item = stack(top) item = stack(top) top = top-1 top = top-1 Return Return

040823040823 2525

Applications of STACKApplications of STACK

Expression EvaluationExpression EvaluationParenthesis CheckerParenthesis CheckerRecursionRecursion

040823040823 2626

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

Operator preecedenceOperator preecedence^ ---------Higher precedence^ ---------Higher precedence--------Next Precedence--------Next Precedence+_-------Least precedence+_-------Least precedence

040823040823 2727

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

The rules to rememberThe rules to remember

11 Parenthesize the expression Parenthesize the expression starting fro left to rightstarting fro left to right

22 During Parenthesizing the During Parenthesizing the

expression the operands associatedexpression the operands associated

with operator having higher with operator having higher

precedence are first parenthesizedprecedence are first parenthesized

040823040823 2828

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

33 The sub-expression which has been The sub-expression which has been converted into postfix is to be converted into postfix is to be treated as single operandtreated as single operand

44 Once the expression is converted to Once the expression is converted to postfix form remove the postfix form remove the parenthesis parenthesis

Example A+BCExample A+BC A+[(B+C)+(D+E)F]GA+[(B+C)+(D+E)F]G Answer ABC+DE+F+G+Answer ABC+DE+F+G+

040823040823 2929

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

Postfix(QP)Postfix(QP) QmdashgtGiven Infix expressionQmdashgtGiven Infix expression P-gtEquivalent Postfix expressionP-gtEquivalent Postfix expression

11 Push ldquo(ldquo onto STACK and add ldquo)rdquo to the Push ldquo(ldquo onto STACK and add ldquo)rdquo to the end of Qend of Q

22 Scan Q from left to right and repeat step 3 Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK to 6 for each element of Q until the STACK is Emptyis Empty

33 If an operand is encountered add it to PIf an operand is encountered add it to P44 If a left parenthesis is encountered push If a left parenthesis is encountered push

it onto STACK it onto STACK

040823040823 3030

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

55 If an operator reg is encountered If an operator reg is encountered thenthen

(a) ADD reg to STACK(a) ADD reg to STACK

[End of IF][End of IF]

(b) Repeatedly pop from STACK and (b) Repeatedly pop from STACK and add P each operator which has add P each operator which has same precedence as or higher same precedence as or higher precedence than regprecedence than reg

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 21: Data structure

040823040823 2121

What is STACK or Pushdown What is STACK or Pushdown ListList

A ordered collection of items A ordered collection of items into which new items may be into which new items may be inserted and from which items inserted and from which items may be deleted at one end may be deleted at one end called the top of stack called the top of stack

040823040823 2222

Operations on STACKOperations on STACK

PUSHWhen item is added in stackPUSHWhen item is added in stack POPWhen item is removed from POPWhen item is removed from

stackstack EMPTYStack containing no itemsEMPTYStack containing no items StackTopDetermine what the top StackTopDetermine what the top

item on a stack without removing item on a stack without removing itthis is a combination of push amp popitthis is a combination of push amp pop

040823040823 2323

Push amp Pop in STACKPush amp Pop in STACK PUSH OperationPUSH Operation PUSHPUSH(STACK TOPMAXITEM) (STACK TOPMAXITEM) STACK--STACK--Name given to ArrayName given to Array TOP----TOP----It contains the location of top It contains the location of top

elementselements MAX---MAX---It is maximum size of STACKIt is maximum size of STACK ITEM---gtValue that is to be store in stack ITEM---gtValue that is to be store in stack

ifif top = MAX top = MAX thenthen stackfull stackfull top = top+1 top = top+1 stack(top) = item stack(top) = item ReturnReturn

040823040823 2424

Push amp Pop in STACKPush amp Pop in STACK

POP OperationPOP Operation

POPPOP(STACK TOPITEM) (STACK TOPITEM)

ifif top = 0 top = 0 thenthen Underflow Underflow item = stack(top) item = stack(top) top = top-1 top = top-1 Return Return

040823040823 2525

Applications of STACKApplications of STACK

Expression EvaluationExpression EvaluationParenthesis CheckerParenthesis CheckerRecursionRecursion

040823040823 2626

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

Operator preecedenceOperator preecedence^ ---------Higher precedence^ ---------Higher precedence--------Next Precedence--------Next Precedence+_-------Least precedence+_-------Least precedence

040823040823 2727

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

The rules to rememberThe rules to remember

11 Parenthesize the expression Parenthesize the expression starting fro left to rightstarting fro left to right

22 During Parenthesizing the During Parenthesizing the

expression the operands associatedexpression the operands associated

with operator having higher with operator having higher

precedence are first parenthesizedprecedence are first parenthesized

040823040823 2828

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

33 The sub-expression which has been The sub-expression which has been converted into postfix is to be converted into postfix is to be treated as single operandtreated as single operand

44 Once the expression is converted to Once the expression is converted to postfix form remove the postfix form remove the parenthesis parenthesis

Example A+BCExample A+BC A+[(B+C)+(D+E)F]GA+[(B+C)+(D+E)F]G Answer ABC+DE+F+G+Answer ABC+DE+F+G+

040823040823 2929

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

Postfix(QP)Postfix(QP) QmdashgtGiven Infix expressionQmdashgtGiven Infix expression P-gtEquivalent Postfix expressionP-gtEquivalent Postfix expression

11 Push ldquo(ldquo onto STACK and add ldquo)rdquo to the Push ldquo(ldquo onto STACK and add ldquo)rdquo to the end of Qend of Q

22 Scan Q from left to right and repeat step 3 Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK to 6 for each element of Q until the STACK is Emptyis Empty

33 If an operand is encountered add it to PIf an operand is encountered add it to P44 If a left parenthesis is encountered push If a left parenthesis is encountered push

it onto STACK it onto STACK

040823040823 3030

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

55 If an operator reg is encountered If an operator reg is encountered thenthen

(a) ADD reg to STACK(a) ADD reg to STACK

[End of IF][End of IF]

(b) Repeatedly pop from STACK and (b) Repeatedly pop from STACK and add P each operator which has add P each operator which has same precedence as or higher same precedence as or higher precedence than regprecedence than reg

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 22: Data structure

040823040823 2222

Operations on STACKOperations on STACK

PUSHWhen item is added in stackPUSHWhen item is added in stack POPWhen item is removed from POPWhen item is removed from

stackstack EMPTYStack containing no itemsEMPTYStack containing no items StackTopDetermine what the top StackTopDetermine what the top

item on a stack without removing item on a stack without removing itthis is a combination of push amp popitthis is a combination of push amp pop

040823040823 2323

Push amp Pop in STACKPush amp Pop in STACK PUSH OperationPUSH Operation PUSHPUSH(STACK TOPMAXITEM) (STACK TOPMAXITEM) STACK--STACK--Name given to ArrayName given to Array TOP----TOP----It contains the location of top It contains the location of top

elementselements MAX---MAX---It is maximum size of STACKIt is maximum size of STACK ITEM---gtValue that is to be store in stack ITEM---gtValue that is to be store in stack

ifif top = MAX top = MAX thenthen stackfull stackfull top = top+1 top = top+1 stack(top) = item stack(top) = item ReturnReturn

040823040823 2424

Push amp Pop in STACKPush amp Pop in STACK

POP OperationPOP Operation

POPPOP(STACK TOPITEM) (STACK TOPITEM)

ifif top = 0 top = 0 thenthen Underflow Underflow item = stack(top) item = stack(top) top = top-1 top = top-1 Return Return

040823040823 2525

Applications of STACKApplications of STACK

Expression EvaluationExpression EvaluationParenthesis CheckerParenthesis CheckerRecursionRecursion

040823040823 2626

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

Operator preecedenceOperator preecedence^ ---------Higher precedence^ ---------Higher precedence--------Next Precedence--------Next Precedence+_-------Least precedence+_-------Least precedence

040823040823 2727

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

The rules to rememberThe rules to remember

11 Parenthesize the expression Parenthesize the expression starting fro left to rightstarting fro left to right

22 During Parenthesizing the During Parenthesizing the

expression the operands associatedexpression the operands associated

with operator having higher with operator having higher

precedence are first parenthesizedprecedence are first parenthesized

040823040823 2828

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

33 The sub-expression which has been The sub-expression which has been converted into postfix is to be converted into postfix is to be treated as single operandtreated as single operand

44 Once the expression is converted to Once the expression is converted to postfix form remove the postfix form remove the parenthesis parenthesis

Example A+BCExample A+BC A+[(B+C)+(D+E)F]GA+[(B+C)+(D+E)F]G Answer ABC+DE+F+G+Answer ABC+DE+F+G+

040823040823 2929

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

Postfix(QP)Postfix(QP) QmdashgtGiven Infix expressionQmdashgtGiven Infix expression P-gtEquivalent Postfix expressionP-gtEquivalent Postfix expression

11 Push ldquo(ldquo onto STACK and add ldquo)rdquo to the Push ldquo(ldquo onto STACK and add ldquo)rdquo to the end of Qend of Q

22 Scan Q from left to right and repeat step 3 Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK to 6 for each element of Q until the STACK is Emptyis Empty

33 If an operand is encountered add it to PIf an operand is encountered add it to P44 If a left parenthesis is encountered push If a left parenthesis is encountered push

it onto STACK it onto STACK

040823040823 3030

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

55 If an operator reg is encountered If an operator reg is encountered thenthen

(a) ADD reg to STACK(a) ADD reg to STACK

[End of IF][End of IF]

(b) Repeatedly pop from STACK and (b) Repeatedly pop from STACK and add P each operator which has add P each operator which has same precedence as or higher same precedence as or higher precedence than regprecedence than reg

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 23: Data structure

040823040823 2323

Push amp Pop in STACKPush amp Pop in STACK PUSH OperationPUSH Operation PUSHPUSH(STACK TOPMAXITEM) (STACK TOPMAXITEM) STACK--STACK--Name given to ArrayName given to Array TOP----TOP----It contains the location of top It contains the location of top

elementselements MAX---MAX---It is maximum size of STACKIt is maximum size of STACK ITEM---gtValue that is to be store in stack ITEM---gtValue that is to be store in stack

ifif top = MAX top = MAX thenthen stackfull stackfull top = top+1 top = top+1 stack(top) = item stack(top) = item ReturnReturn

040823040823 2424

Push amp Pop in STACKPush amp Pop in STACK

POP OperationPOP Operation

POPPOP(STACK TOPITEM) (STACK TOPITEM)

ifif top = 0 top = 0 thenthen Underflow Underflow item = stack(top) item = stack(top) top = top-1 top = top-1 Return Return

040823040823 2525

Applications of STACKApplications of STACK

Expression EvaluationExpression EvaluationParenthesis CheckerParenthesis CheckerRecursionRecursion

040823040823 2626

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

Operator preecedenceOperator preecedence^ ---------Higher precedence^ ---------Higher precedence--------Next Precedence--------Next Precedence+_-------Least precedence+_-------Least precedence

040823040823 2727

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

The rules to rememberThe rules to remember

11 Parenthesize the expression Parenthesize the expression starting fro left to rightstarting fro left to right

22 During Parenthesizing the During Parenthesizing the

expression the operands associatedexpression the operands associated

with operator having higher with operator having higher

precedence are first parenthesizedprecedence are first parenthesized

040823040823 2828

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

33 The sub-expression which has been The sub-expression which has been converted into postfix is to be converted into postfix is to be treated as single operandtreated as single operand

44 Once the expression is converted to Once the expression is converted to postfix form remove the postfix form remove the parenthesis parenthesis

Example A+BCExample A+BC A+[(B+C)+(D+E)F]GA+[(B+C)+(D+E)F]G Answer ABC+DE+F+G+Answer ABC+DE+F+G+

040823040823 2929

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

Postfix(QP)Postfix(QP) QmdashgtGiven Infix expressionQmdashgtGiven Infix expression P-gtEquivalent Postfix expressionP-gtEquivalent Postfix expression

11 Push ldquo(ldquo onto STACK and add ldquo)rdquo to the Push ldquo(ldquo onto STACK and add ldquo)rdquo to the end of Qend of Q

22 Scan Q from left to right and repeat step 3 Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK to 6 for each element of Q until the STACK is Emptyis Empty

33 If an operand is encountered add it to PIf an operand is encountered add it to P44 If a left parenthesis is encountered push If a left parenthesis is encountered push

it onto STACK it onto STACK

040823040823 3030

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

55 If an operator reg is encountered If an operator reg is encountered thenthen

(a) ADD reg to STACK(a) ADD reg to STACK

[End of IF][End of IF]

(b) Repeatedly pop from STACK and (b) Repeatedly pop from STACK and add P each operator which has add P each operator which has same precedence as or higher same precedence as or higher precedence than regprecedence than reg

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 24: Data structure

040823040823 2424

Push amp Pop in STACKPush amp Pop in STACK

POP OperationPOP Operation

POPPOP(STACK TOPITEM) (STACK TOPITEM)

ifif top = 0 top = 0 thenthen Underflow Underflow item = stack(top) item = stack(top) top = top-1 top = top-1 Return Return

040823040823 2525

Applications of STACKApplications of STACK

Expression EvaluationExpression EvaluationParenthesis CheckerParenthesis CheckerRecursionRecursion

040823040823 2626

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

Operator preecedenceOperator preecedence^ ---------Higher precedence^ ---------Higher precedence--------Next Precedence--------Next Precedence+_-------Least precedence+_-------Least precedence

040823040823 2727

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

The rules to rememberThe rules to remember

11 Parenthesize the expression Parenthesize the expression starting fro left to rightstarting fro left to right

22 During Parenthesizing the During Parenthesizing the

expression the operands associatedexpression the operands associated

with operator having higher with operator having higher

precedence are first parenthesizedprecedence are first parenthesized

040823040823 2828

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

33 The sub-expression which has been The sub-expression which has been converted into postfix is to be converted into postfix is to be treated as single operandtreated as single operand

44 Once the expression is converted to Once the expression is converted to postfix form remove the postfix form remove the parenthesis parenthesis

Example A+BCExample A+BC A+[(B+C)+(D+E)F]GA+[(B+C)+(D+E)F]G Answer ABC+DE+F+G+Answer ABC+DE+F+G+

040823040823 2929

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

Postfix(QP)Postfix(QP) QmdashgtGiven Infix expressionQmdashgtGiven Infix expression P-gtEquivalent Postfix expressionP-gtEquivalent Postfix expression

11 Push ldquo(ldquo onto STACK and add ldquo)rdquo to the Push ldquo(ldquo onto STACK and add ldquo)rdquo to the end of Qend of Q

22 Scan Q from left to right and repeat step 3 Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK to 6 for each element of Q until the STACK is Emptyis Empty

33 If an operand is encountered add it to PIf an operand is encountered add it to P44 If a left parenthesis is encountered push If a left parenthesis is encountered push

it onto STACK it onto STACK

040823040823 3030

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

55 If an operator reg is encountered If an operator reg is encountered thenthen

(a) ADD reg to STACK(a) ADD reg to STACK

[End of IF][End of IF]

(b) Repeatedly pop from STACK and (b) Repeatedly pop from STACK and add P each operator which has add P each operator which has same precedence as or higher same precedence as or higher precedence than regprecedence than reg

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 25: Data structure

040823040823 2525

Applications of STACKApplications of STACK

Expression EvaluationExpression EvaluationParenthesis CheckerParenthesis CheckerRecursionRecursion

040823040823 2626

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

Operator preecedenceOperator preecedence^ ---------Higher precedence^ ---------Higher precedence--------Next Precedence--------Next Precedence+_-------Least precedence+_-------Least precedence

040823040823 2727

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

The rules to rememberThe rules to remember

11 Parenthesize the expression Parenthesize the expression starting fro left to rightstarting fro left to right

22 During Parenthesizing the During Parenthesizing the

expression the operands associatedexpression the operands associated

with operator having higher with operator having higher

precedence are first parenthesizedprecedence are first parenthesized

040823040823 2828

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

33 The sub-expression which has been The sub-expression which has been converted into postfix is to be converted into postfix is to be treated as single operandtreated as single operand

44 Once the expression is converted to Once the expression is converted to postfix form remove the postfix form remove the parenthesis parenthesis

Example A+BCExample A+BC A+[(B+C)+(D+E)F]GA+[(B+C)+(D+E)F]G Answer ABC+DE+F+G+Answer ABC+DE+F+G+

040823040823 2929

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

Postfix(QP)Postfix(QP) QmdashgtGiven Infix expressionQmdashgtGiven Infix expression P-gtEquivalent Postfix expressionP-gtEquivalent Postfix expression

11 Push ldquo(ldquo onto STACK and add ldquo)rdquo to the Push ldquo(ldquo onto STACK and add ldquo)rdquo to the end of Qend of Q

22 Scan Q from left to right and repeat step 3 Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK to 6 for each element of Q until the STACK is Emptyis Empty

33 If an operand is encountered add it to PIf an operand is encountered add it to P44 If a left parenthesis is encountered push If a left parenthesis is encountered push

it onto STACK it onto STACK

040823040823 3030

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

55 If an operator reg is encountered If an operator reg is encountered thenthen

(a) ADD reg to STACK(a) ADD reg to STACK

[End of IF][End of IF]

(b) Repeatedly pop from STACK and (b) Repeatedly pop from STACK and add P each operator which has add P each operator which has same precedence as or higher same precedence as or higher precedence than regprecedence than reg

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 26: Data structure

040823040823 2626

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

Operator preecedenceOperator preecedence^ ---------Higher precedence^ ---------Higher precedence--------Next Precedence--------Next Precedence+_-------Least precedence+_-------Least precedence

040823040823 2727

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

The rules to rememberThe rules to remember

11 Parenthesize the expression Parenthesize the expression starting fro left to rightstarting fro left to right

22 During Parenthesizing the During Parenthesizing the

expression the operands associatedexpression the operands associated

with operator having higher with operator having higher

precedence are first parenthesizedprecedence are first parenthesized

040823040823 2828

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

33 The sub-expression which has been The sub-expression which has been converted into postfix is to be converted into postfix is to be treated as single operandtreated as single operand

44 Once the expression is converted to Once the expression is converted to postfix form remove the postfix form remove the parenthesis parenthesis

Example A+BCExample A+BC A+[(B+C)+(D+E)F]GA+[(B+C)+(D+E)F]G Answer ABC+DE+F+G+Answer ABC+DE+F+G+

040823040823 2929

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

Postfix(QP)Postfix(QP) QmdashgtGiven Infix expressionQmdashgtGiven Infix expression P-gtEquivalent Postfix expressionP-gtEquivalent Postfix expression

11 Push ldquo(ldquo onto STACK and add ldquo)rdquo to the Push ldquo(ldquo onto STACK and add ldquo)rdquo to the end of Qend of Q

22 Scan Q from left to right and repeat step 3 Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK to 6 for each element of Q until the STACK is Emptyis Empty

33 If an operand is encountered add it to PIf an operand is encountered add it to P44 If a left parenthesis is encountered push If a left parenthesis is encountered push

it onto STACK it onto STACK

040823040823 3030

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

55 If an operator reg is encountered If an operator reg is encountered thenthen

(a) ADD reg to STACK(a) ADD reg to STACK

[End of IF][End of IF]

(b) Repeatedly pop from STACK and (b) Repeatedly pop from STACK and add P each operator which has add P each operator which has same precedence as or higher same precedence as or higher precedence than regprecedence than reg

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 27: Data structure

040823040823 2727

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

The rules to rememberThe rules to remember

11 Parenthesize the expression Parenthesize the expression starting fro left to rightstarting fro left to right

22 During Parenthesizing the During Parenthesizing the

expression the operands associatedexpression the operands associated

with operator having higher with operator having higher

precedence are first parenthesizedprecedence are first parenthesized

040823040823 2828

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

33 The sub-expression which has been The sub-expression which has been converted into postfix is to be converted into postfix is to be treated as single operandtreated as single operand

44 Once the expression is converted to Once the expression is converted to postfix form remove the postfix form remove the parenthesis parenthesis

Example A+BCExample A+BC A+[(B+C)+(D+E)F]GA+[(B+C)+(D+E)F]G Answer ABC+DE+F+G+Answer ABC+DE+F+G+

040823040823 2929

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

Postfix(QP)Postfix(QP) QmdashgtGiven Infix expressionQmdashgtGiven Infix expression P-gtEquivalent Postfix expressionP-gtEquivalent Postfix expression

11 Push ldquo(ldquo onto STACK and add ldquo)rdquo to the Push ldquo(ldquo onto STACK and add ldquo)rdquo to the end of Qend of Q

22 Scan Q from left to right and repeat step 3 Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK to 6 for each element of Q until the STACK is Emptyis Empty

33 If an operand is encountered add it to PIf an operand is encountered add it to P44 If a left parenthesis is encountered push If a left parenthesis is encountered push

it onto STACK it onto STACK

040823040823 3030

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

55 If an operator reg is encountered If an operator reg is encountered thenthen

(a) ADD reg to STACK(a) ADD reg to STACK

[End of IF][End of IF]

(b) Repeatedly pop from STACK and (b) Repeatedly pop from STACK and add P each operator which has add P each operator which has same precedence as or higher same precedence as or higher precedence than regprecedence than reg

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 28: Data structure

040823040823 2828

Infix To Postfix Conversion of Infix To Postfix Conversion of an Arithmetic Expressionan Arithmetic Expression

33 The sub-expression which has been The sub-expression which has been converted into postfix is to be converted into postfix is to be treated as single operandtreated as single operand

44 Once the expression is converted to Once the expression is converted to postfix form remove the postfix form remove the parenthesis parenthesis

Example A+BCExample A+BC A+[(B+C)+(D+E)F]GA+[(B+C)+(D+E)F]G Answer ABC+DE+F+G+Answer ABC+DE+F+G+

040823040823 2929

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

Postfix(QP)Postfix(QP) QmdashgtGiven Infix expressionQmdashgtGiven Infix expression P-gtEquivalent Postfix expressionP-gtEquivalent Postfix expression

11 Push ldquo(ldquo onto STACK and add ldquo)rdquo to the Push ldquo(ldquo onto STACK and add ldquo)rdquo to the end of Qend of Q

22 Scan Q from left to right and repeat step 3 Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK to 6 for each element of Q until the STACK is Emptyis Empty

33 If an operand is encountered add it to PIf an operand is encountered add it to P44 If a left parenthesis is encountered push If a left parenthesis is encountered push

it onto STACK it onto STACK

040823040823 3030

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

55 If an operator reg is encountered If an operator reg is encountered thenthen

(a) ADD reg to STACK(a) ADD reg to STACK

[End of IF][End of IF]

(b) Repeatedly pop from STACK and (b) Repeatedly pop from STACK and add P each operator which has add P each operator which has same precedence as or higher same precedence as or higher precedence than regprecedence than reg

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 29: Data structure

040823040823 2929

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

Postfix(QP)Postfix(QP) QmdashgtGiven Infix expressionQmdashgtGiven Infix expression P-gtEquivalent Postfix expressionP-gtEquivalent Postfix expression

11 Push ldquo(ldquo onto STACK and add ldquo)rdquo to the Push ldquo(ldquo onto STACK and add ldquo)rdquo to the end of Qend of Q

22 Scan Q from left to right and repeat step 3 Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK to 6 for each element of Q until the STACK is Emptyis Empty

33 If an operand is encountered add it to PIf an operand is encountered add it to P44 If a left parenthesis is encountered push If a left parenthesis is encountered push

it onto STACK it onto STACK

040823040823 3030

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

55 If an operator reg is encountered If an operator reg is encountered thenthen

(a) ADD reg to STACK(a) ADD reg to STACK

[End of IF][End of IF]

(b) Repeatedly pop from STACK and (b) Repeatedly pop from STACK and add P each operator which has add P each operator which has same precedence as or higher same precedence as or higher precedence than regprecedence than reg

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 30: Data structure

040823040823 3030

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

55 If an operator reg is encountered If an operator reg is encountered thenthen

(a) ADD reg to STACK(a) ADD reg to STACK

[End of IF][End of IF]

(b) Repeatedly pop from STACK and (b) Repeatedly pop from STACK and add P each operator which has add P each operator which has same precedence as or higher same precedence as or higher precedence than regprecedence than reg

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 31: Data structure

040823040823 3131

Algorithm for Conversing Infix Algorithm for Conversing Infix Expression to Postfix FormExpression to Postfix Form

66 If a right parenthesis is encountered thenIf a right parenthesis is encountered then(a) Repeatedly pop from STACK and add to P (a) Repeatedly pop from STACK and add to P

each operator until a left parenthesis is each operator until a left parenthesis is encounteredencountered

(b) Remove the left parenthesis do not add (b) Remove the left parenthesis do not add it of P]it of P]

[End of If][End of If][End of step 2 loop][End of step 2 loop]77 Exit Exit

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 32: Data structure

040823040823 3232

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

11 Reverse the input stringReverse the input string

22 Examine the next element in Examine the next element in the inputthe input

33 If it is operand add it to the If it is operand add it to the output stringoutput string

44 If it is closing parenthesis push If it is closing parenthesis push it on STACKit on STACK

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 33: Data structure

040823040823 3333

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

55 If it is operator thenIf it is operator then

i) if STACK is empty push ndashoperation on i) if STACK is empty push ndashoperation on STACKSTACK

ii) if the top of the stack is closing ii) if the top of the stack is closing parenthesis push operator on STACKparenthesis push operator on STACK

iii) if it has same or higher priority then iii) if it has same or higher priority then the top of STACK push operator on Sthe top of STACK push operator on S

iv) else pop the operator from the STACK iv) else pop the operator from the STACK and add it to output string repeat Sand add it to output string repeat S

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 34: Data structure

040823040823 3434

Converting Infix Expression to Converting Infix Expression to Prefix ExpressionPrefix Expression

66 If it is a opening parenthesis pop If it is a opening parenthesis pop operator from STACK and add them operator from STACK and add them to S until a closing parenthesis is to S until a closing parenthesis is encountered POP and discard the encountered POP and discard the closing parenthesisclosing parenthesis

77 If there is more input go to step 2If there is more input go to step 288 If there is more input unstack the If there is more input unstack the

remaining operators and add themremaining operators and add them99 Reverse the output stringReverse the output string

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 35: Data structure

040823040823 3535

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

This algorithm finds the value of an This algorithm finds the value of an arithmetic expressions P written in arithmetic expressions P written in postfix notation The algorithm uses apostfix notation The algorithm uses aSTACK to hold operands evaluate PSTACK to hold operands evaluate P11 Add right parenthesis ldquo)rdquo at the end Add right parenthesis ldquo)rdquo at the end

of P[This acts as sentinel]of P[This acts as sentinel]22 Scan P from left to right and repeat Scan P from left to right and repeat

step 3 amp 4 for each element of P step 3 amp 4 for each element of P until the sentinel ldquo)rdquo is until the sentinel ldquo)rdquo is encounteredencountered

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 36: Data structure

040823040823 3636

Algorithm to Evaluate a Postfix Algorithm to Evaluate a Postfix ExpressionExpression

33 If an operand is encountered put it on If an operand is encountered put it on STACKSTACK

44 If an operator reg is encountered thenIf an operator reg is encountered thenA) Remove the two top elements of STACK A) Remove the two top elements of STACK Where A is the top element and B is the next-Where A is the top element and B is the next-to-top elementto-top elementB)Evaluate B regAB)Evaluate B regAC)Place the result of (b) back o STACKC)Place the result of (b) back o STACK[End of IF][End of IF][End of step 2 loop][End of step 2 loop]

66 Set value equal to the top element on STACKSet value equal to the top element on STACK77 Exit Exit

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 37: Data structure

040823040823 3737

Parenthesis CheckerParenthesis Checker Read expRead exp Create empty StackCreate empty Stack For each character C in expFor each character C in exp If(current character is left symbol) thenIf(current character is left symbol) then Push the character C onto StackPush the character C onto Stack Elseif(current character C is a right Elseif(current character C is a right

Symbol)thenSymbol)then If(stack is empty)thenIf(stack is empty)then PrintrdquoErrorNo matching open symbolrdquoPrintrdquoErrorNo matching open symbolrdquo ExitExit

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 38: Data structure

040823040823 3838

Parenthesis CheckerParenthesis Checker

ElseElse POP a symbol S from the StackPOP a symbol S from the Stack If (S doesnot correspond to C)thenIf (S doesnot correspond to C)then PrintrdquoErrorIncorrect nesting of symbolsrdquoPrintrdquoErrorIncorrect nesting of symbolsrdquo ExitExit EndifEndif EndifEndif EndifEndif End forEnd for

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 39: Data structure

040823040823 3939

Parenthesis CheckerParenthesis Checker

If (stack is not empty)then If (stack is not empty)then PrintrdquoErrorMissing closing PrintrdquoErrorMissing closing

symbols(s)rdquosymbols(s)rdquo ElseElse PrintrdquoInput expression is okrdquoPrintrdquoInput expression is okrdquo EndifEndif EndEnd

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 40: Data structure

040823040823 4040

Example of STACKExample of STACK Many computer algorithms work best with stacks --- stacks are Many computer algorithms work best with stacks --- stacks are

used for used for remembering partially completed tasks and remembering partially completed tasks and undoing (backtracking from) an action undoing (backtracking from) an action An example of 1 is described in the next section where sub An example of 1 is described in the next section where sub

expressions of an arithmetic expression are remembered for later expressions of an arithmetic expression are remembered for later computation Another example is presented in the next lecture computation Another example is presented in the next lecture where we see how the Java Virtual Machine uses a stack to where we see how the Java Virtual Machine uses a stack to remember all of a programs methods that have been called but remember all of a programs methods that have been called but are not yet finished are not yet finished

An example of 2 is the ``undo button on most text editors which An example of 2 is the ``undo button on most text editors which lets a person undo a typing error or the ``back button on a web lets a person undo a typing error or the ``back button on a web browser which lets a user backtrack to a previous web page browser which lets a user backtrack to a previous web page Another example is a searching algorithm which searches a maze Another example is a searching algorithm which searches a maze and keeps a history of its moves in a stack If the algorithm makes and keeps a history of its moves in a stack If the algorithm makes a false (bad) move the move can be undone by retrieving the a false (bad) move the move can be undone by retrieving the previous position from the stack previous position from the stack

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 41: Data structure

040823040823 4141

STACK ImplementationSTACK Implementation Static and dynamic data structures A stack can be stored in bull a static data structure OR bull a dynamic data structure Static data structures These define collections of data which are fixed in size

when the program is compiled An array is a static data structure Dynamic data structures These define collections of data which are variable in size

and structure They are created as the program executes and grow and shrink to

accommodate the data being stored

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 42: Data structure

040823040823 4242

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

includeltstdiohgtincludeltstdiohgt includeltconiohgtincludeltconiohgt transpose for the sparse matrix transpose for the sparse matrix void main()void main() clrscr()clrscr() int a[10][10]b[10][10]int a[10][10]b[10][10] int mnpqtcolint mnpqtcol int ijint ij

printf(enter the no of row and columns n)printf(enter the no of row and columns n) scanf(d dampmampn)scanf(d dampmampn)

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 43: Data structure

040823040823 4343

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

assigning the value of matrix assigning the value of matrix for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(a[d][d]= ij)printf(a[d][d]= ij) scanf(dampa[i][j])scanf(dampa[i][j])

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 44: Data structure

040823040823 4444

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

printf(nn)printf(nn) displaying the matrixdisplaying the matrix printf(nnThe matrix is nn)printf(nnThe matrix is nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) printf(da[i][j])printf(da[i][j]) printf(n)printf(n)

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 45: Data structure

040823040823 4545

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=0t=0 printf(nnthe non zero value matrix are nn)printf(nnthe non zero value matrix are nn) for(i=1ilt=mi++)for(i=1ilt=mi++) for(j=1jlt=nj++)for(j=1jlt=nj++) accepting only non zero value accepting only non zero value if(a[i][j]=0)if(a[i][j]=0)

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 46: Data structure

040823040823 4646

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

t=t+1t=t+1 b[t][1]=ib[t][1]=i b[t][2]=jb[t][2]=j b[t][3]=a[i][j]b[t][3]=a[i][j] b[0][0]=mb[0][0]=m b[0][1]=nb[0][1]=n b[0][2]=tb[0][2]=t displaying the matrix of non-zero value displaying the matrix of non-zero value printf(n)printf(n) For(i=0ilt=ti++)For(i=0ilt=ti++) printf(ldquod ldquoa[i][0]a[i][1]a[i][2])printf(ldquod ldquoa[i][0]a[i][1]a[i][2])

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 47: Data structure

040823040823 4747

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

transpose of the matrix transpose of the matrix printf(nnthe transpose of the matrix n )printf(nnthe transpose of the matrix n ) if(tgt0)if(tgt0) for(i=1ilt=ni++)for(i=1ilt=ni++) for(j=1jlt=tj++)for(j=1jlt=tj++) if(b[j][2]==i)if(b[j][2]==i) a[q][1]=b[j][2] a[q][2]=b[j][1]a[q][1]=b[j][2] a[q][2]=b[j][1] a[q][3]=b[j][3] q=q+1a[q][3]=b[j][3] q=q+1

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 48: Data structure

040823040823 4848

TRANSPOSE OF SPARSE TRANSPOSE OF SPARSE MATRIXMATRIX

for(i=0ilt=ti++)for(i=0ilt=ti++) printf(a[d d d dnia[i][1]a[i][2]a[i][3])printf(a[d d d dnia[i][1]a[i][2]a[i][3]) getch()getch()

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 49: Data structure

040823040823 4949

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack) Recursion amp Stack)

This problem is not specified in terms This problem is not specified in terms of recursion but the recursive of recursion but the recursive technique can be used to produce a technique can be used to produce a logical solution logical solution

Problem DefinitionProblem Definition There are three pegs ABamp C exist There are three pegs ABamp C exist

any number of disks (n) of different any number of disks (n) of different diameters are placed on peg A so diameters are placed on peg A so that a larger disk is always below a that a larger disk is always below a smaller disksmaller disk

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 50: Data structure

040823040823 5050

Tower of Hanoi(An application of Tower of Hanoi(An application of Recursion amp Stack)Recursion amp Stack)

The object is to move n disks to peg The object is to move n disks to peg C using peg B as auxiliaryC using peg B as auxiliary

Only the top disk on any peg may be Only the top disk on any peg may be moved to any other peg and a larger moved to any other peg and a larger disk may never rest on a smaller disk may never rest on a smaller oneone

Notein general it requires f(n)=2Notein general it requires f(n)=2nn-1 -1 moves moves

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 51: Data structure

040823040823 5151

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

To move n disks from A to To move n disks from A to C using B as auxiliaryC using B as auxiliary

11 If n==1 move the single disk If n==1 move the single disk from A to C and stopfrom A to C and stop

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 52: Data structure

040823040823 5252

Recursive solution to tower of Recursive solution to tower of Hanoi problemHanoi problem

22 Move the top n-1 disks from Move the top n-1 disks from A to B using C as auxiliaryA to B using C as auxiliary

33 Move the remaining disks Move the remaining disks from A to Cfrom A to C

44 Move the n-1 disks from B to Move the n-1 disks from B to Cusing A as auxiliaryCusing A as auxiliary

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 53: Data structure

040823040823 5353

Recursive Implementation of Tower Recursive Implementation of Tower of Hanoiof Hanoi

main()main()

int nint n

scanf (ldquodrdquo ampn)scanf (ldquodrdquo ampn)

towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)towers (n rsquoArsquo rsquoCrsquo rsquoBrsquo)

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 54: Data structure

040823040823 5454

towers(int n char frompeg char towers(int n char frompeg char topegchar auxpeg)topegchar auxpeg)

If (n==1)If (n==1)printf (ldquon s c s crdquo ldquomove disk 1 printf (ldquon s c s crdquo ldquomove disk 1

from peg ldquofrompeg ldquoto pegrdquo topeg)from peg ldquofrompeg ldquoto pegrdquo topeg)returnreturn

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)

Page 55: Data structure

040823040823 5555

towers(n-1frompegauxpegtopeg)towers(n-1frompegauxpegtopeg)

printf (ldquon s d s c s crdquo printf (ldquon s d s c s crdquo ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquomove diskrdquo n ldquofrom pegrdquo frompeg ldquoto pegrdquo topeg)ldquoto pegrdquo topeg)

tower(n-1auxpegtopegfrompeg)tower(n-1auxpegtopegfrompeg)