This preview shows pages 1–7. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: 20012009 M. D. Evans All Rights Reserved 1 Ch. 4 Special Types of Lists Part A: Stacks: 4.1 Introduction: Def : a stack is an ordered set of elements with all insertions/deletions at one end, together with the operations: create ()  initialize a new empty stack isEmpty ()  is stack S empty? push (x)  insert item X on top of stack pop (x)  delete stacktop item and put in x stacktop (x)  use x to lookat stacktop item Attributes of a stack: • top of stack • list of elements in the stack • size? Note: 1. Called pushdown list or LIFO structure. 2. Implicit in above is notion of a pointer called stacktop (which always points to top item or in some implementations, points to where next push would place item). 20012009 M. D. Evans All Rights Reserved 2 4.2 Applications: many and varied! 1. data reversals: push pop cat t tac a c 2. testing for palindromes : (ie. otto; madam, I’m adam) push stack push k c a t s k c a t s s t a c k stack 1 stack 2 stack 3 successively pop and compare 20012009 M. D. Evans All Rights Reserved 3 3. subprogram invocations: main prog system stack 4. parenthesis pairing: abc(de(fgh+i)(j+k(l+m)+n)) b WHILE not end_of_string DO IF next character is a ‘(’ THEN s.push ( ‘(’ ) ELSEIF the characteris a ‘)’ THEN s.pop (x) ENDIF s.isEmpty() 20012009 M. D. Evans All Rights Reserved 4 5. evaluating postfix expressions: PREFIX INFIX POSTFIX +AB A+B AB+ + * ABC (A * B)+C AB * C+ +A * BC A*B * C ABC * + * +ABCD (A+B) * (CD) AB+CD * Ex: ABC+/DEF*+ STACK TIME Note: Also need to define ‘commutativety’. ie. B / ⇒ B/A or A/B ?? A 20012009 M. D. Evans All Rights Reserved 5 6. converting infix to postfix: Note: 1. Operands in same order in both. 2. Operators move only to right of operands. A * (B+C) → ABC + * 3. All parentheses removed. b Conversion = where to place operator. b highlevel algorithm 1: For each token in infix expression CASE token of operand : append to postfix string operator : save it until decide where to place it ‘(’ , ‘)’ : discard it ENDCASE 20012009 M. D. Evans All Rights Reserved 6 BUT: can’t just discard ‘(‘ & ‘)’ because they determine where operators go, since (~)is its own isolated infix expression....
View
Full
Document
This note was uploaded on 05/13/2010 for the course CMPT 225 taught by Professor Annelavergne during the Spring '07 term at Simon Fraser.
 Spring '07
 AnneLavergne

Click to edit the document details