470 likes | 479 Views
Understand stack operations, implementation, and applications using arrays. Learn to manage recursion and solve problems efficiently. This session is designed for in-depth learning and practical problem-solving techniques.
E N D
TK1924 Program Design & Problem SolvingSession 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
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
Stack Operations • In the abstract class stackADT: • initializeStack • isEmptyStack • isFullStack • push • top • pop
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
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
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
Empty Stack • If stackTop is 0, the stack is empty
Full Stack • The stack is full if stackTop is equal to maxStackSize
Push • Store the newItem in the array component indicated by stackTop • Increment stackTop • Must avoid an overflow
Pop • Simply decrement stackTop by 1 • Must check for underflow condition
Stack Header File myStack.h • Place definitions of class and functions (stack operations) together in a file
Programming Example: Highest GPA • Input: program reads an input file with each student’s GPA and name 3.5 Bill 3.6 John 2.7 Lisa 3.9 Kathy 3.4 Jason 3.9 David 3.4 Jack • Output: the highest GPA and all the names associated with the highest GPA
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
Programming Example: Problem Analysis and Algorithm Design (cont’d.) 3.5 Bill 3.6 John 2.7 Lisa 3.9 Kathy 3.4 Jason 3.9 David 3.4 Jack 3.9 [99] [98] highestGPA : : [3] maxStackSize [2] 100 stackTop David [1] 1 list Kathy [0]
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
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: + ab
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: abc * +
Application of Stacks: Postfix Expressions Calculator (cont'd.)
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
Example: 6 3 + 2 * = Application of Stacks: Postfix Expressions Calculator (cont'd.)
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
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
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
Main Algorithm • Pseudocode: • We will write four functions: • evaluateExpression, evaluateOpr, discardExp, and printResult
Function discardExp • This function is called whenever an error is discovered in the expression
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
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)
Nonrecursive Algorithm to Print a Linked List Backward • Let us now execute the following statements: • Output: 20 15 10 5
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)