TK1924 Program Design & Problem Solving Session 2011/2012 L5: Stacks.

Post on 26-Mar-2015

219 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

Transcript

TK1924 Program Design & Problem Solving

Session 2011/2012

L5: Stacks

Objectives

In this chapter, you will:• Learn about stacks• Examine various stack operations• Learn how to implement a stack as an array• Discover stack applications• Learn how to use a stack to remove recursion

2

Stacks

• Stack: list of homogenous elements– Addition and deletion occur only at one end,

called the top of the stack• Example: in a cafeteria, the second tray can be

removed only if first tray has been removed

– Last in first out (LIFO) data structure

• Operations:– Push: to add an element onto the stack– Pop: to remove an element from the stack

3

4

Stacks (cont’d.)

5

Stacks (cont’d.)

Stack Operations

• In the abstract class stackADT:– initializeStack– isEmptyStack– isFullStack– push– top– pop

6

Implementation of Stacks as Arrays

• First element can go in first array position, the second in the second position, etc.

• The top of the stack is the index of the last element added to the stack

• Stack elements are stored in an array• Stack element is accessed only through top• To keep track of the top position, use a

variable called stackTop

7

Implementation of Stacks as Arrays (cont'd.)

• Because stack is homogeneous– You can use an array to implement a stack

• Can dynamically allocate array– Enables user to specify size of the array

• The class stackType implements the functions of the abstract class stackADT

8

UML Class Diagram of class stackType

9

Implementation of Stacks as Arrays (cont'd.)

• C++ arrays begin with the index 0– Must distinguish between:

• The value of stackTop• The array position indicated by stackTop

• If stackTop is 0, the stack is empty

• If stackTop is nonzero, the stack is not empty– The top element is given by stackTop - 1

10

Implementation of Stacks as Arrays (cont'd.)

11

Initialize Stack

12

Empty Stack

• If stackTop is 0, the stack is empty

13

Full Stack

• The stack is full if stackTop is equal to maxStackSize

14

Push

• Store the newItem in the array component indicated by stackTop

• Increment stackTop• Must avoid an overflow

15

Push (cont'd.)

16

Return the Top Element

17

Pop

• Simply decrement stackTop by 1• Must check for underflow condition

18

Pop (cont’d.)

19

Pop (cont’d.)

20

Copy Stack

21

Constructor

22

23

Destructor

Stack Header File

myStack.h– Place definitions of class and functions (stack

operations) together in a file

24

Programming Example: Highest GPA

• Input: program reads an input file with each student’s GPA and name3.5 Bill3.6 John2.7 Lisa3.9 Kathy3.4 Jason3.9 David3.4 Jack

• Output: the highest GPA and all the names associated with the highest GPA

25

Programming Example: Problem Analysis and Algorithm Design

• Read the first GPA and name of the student – This is the highest GPA so far

• Read the second GPA and student name– Compare this GPA with highest GPA so far

• New GPA is greater than highest GPA so far– Update highest GPA, initialize stack, add to stack

• New GPA is equal to the highest GPA so far– Add name to stack

• New GPA is smaller than the highest GPA– Discard

26

27

Programming Example: Problem Analysis and Algorithm Design (cont’d.)

3.5 Bill3.6 John2.7 Lisa3.9 Kathy3.4 Jason3.9 David3.4 Jack

highestGPA

3.9

Kathy

David

1

100

[0]

[1]

[2]

[3]

:

:

[98]

[99]

Application of Stacks: Postfix Expressions Calculator

• Infix notation: usual notation for writing arithmetic expressions– The operator is written between the operands– Example: a + b– The operators have precedence

• Parentheses can be used to override precedence

28

Application of Stacks: Postfix Expressions Calculator (cont'd.)

• Prefix (Polish) notation: the operators are written before the operands– Introduced by the Polish mathematician Jan

Lukasiewicz• Early 1920s

– The parentheses can be omitted– Example: + a b

29

Application of Stacks: Postfix Expressions Calculator (cont'd.)

• Reverse Polish notation: the operators follow the operands (postfix operators)– Proposed by the Australian philosopher and

early computer scientist Charles L. Hamblin• Late 1950's

– Advantage: the operators appear in the order required for computation

– Example: a + b * c • In a postfix expression: a b c * +

30

Application of Stacks: Postfix Expressions Calculator (cont'd.)

31

Application of Stacks: Postfix Expressions Calculator (cont'd.)

• Postfix notation has important applications in computer science– Many compilers first translate arithmetic

expressions into postfix notation and then translate this expression into machine code

• Evaluation algorithm:– Scan expression from left to right– When an operator is found, back up to get the

operands, perform the operation, and continue

32

Application of Stacks: Postfix Expressions Calculator (cont'd.)

33

• Example: 6 3 + 2 * =

Application of Stacks: Postfix Expressions Calculator (cont'd.)

• Symbols can be numbers or anything else:– +, -, *, and / are operators

• Pop stack twice and evaluate expression• If stack has less than two elements error

– If symbol is =, the expression ends• Pop and print answer from stack• If stack has more than one element error

– If symbol is anything else• Expression contains an illegal operator

34

Application of Stacks: Postfix Expressions Calculator (cont'd.)

• Examples:7 6 + 3 ; 6 - =

• ; is an illegal operator

14 + 2 3 * =• Does not have enough operands for +

14 2 3 + =• Error: stack will have two elements when we

encounter equal (=) sign

35

Application of Stacks: Postfix Expressions Calculator (cont'd.)

• We assume that the postfix expressions are in the following form:

#6 #3 + #2 * =

– If symbol scanned is #, next input is a number– If the symbol scanned is not #, then it is:

• An operator (may be illegal) or• An equal sign (end of expression)

• We assume expressions contain only +, -, *, and / operators

36

Main Algorithm

• Pseudocode:

• We will write four functions:– evaluateExpression, evaluateOpr, discardExp, and printResult

37

Function evaluateExpression

38

Function evaluateOpr

39

40

Function evaluateOpr (cont’d.)

Function discardExp

• This function is called whenever an error is discovered in the expression

41

Function printResult

• If the postfix expression contains no errors, the function printResult prints the result– Otherwise, it outputs an appropriate message

• The result of the expression is in the stack and the output is sent to a file

42

43

Function printResult (cont’d.)

Nonrecursive Algorithm to Print a Linked List Backward

• To print the list backward, first we need to get to the last node of the list– Problem: how do we get back to previous node?

• Links go in only one direction

– Solution: save a pointer to each of the nodes with info 5, 10, and 15

• Use a stack (LIFO)

44

45

Nonrecursive Algorithm to Print a Linked List Backward

• Let us now execute the following statements:

• Output:20 15 10 5

46

Nonrecursive Algorithm to Print a Linked List Backward

Summary

• Stack: items are added/deleted from one end– Last In First Out (LIFO) data structure– Operations: push, pop, initialize, destroy,

check for empty/full stack– Can be implemented as array or linked list– Middle elements should not be accessed

• Postfix notation: operators are written after the operands (no parentheses needed)

47

top related