Download presentation
Presentation is loading. Please wait.
1
CE 221 Data Structures and Algorithms
Chapter 3: Lists, Stacks, and Queues - II Text: Read Weiss, §3.6 Izmir University of Economics
2
The Stack ADT – Stack Model
A stack (LIFO list) is a list with the restriction that inserts and deletes can be performed in only one position, namely the end of the list called the top. The two operations on a stack are push, pop (also top to examine the item at the top). While pop on an empty stack is generally considered an ADT error, running out of space when performing a push is an implementation error but not an ADT error. Izmir University of Economics
3
Implementation of Stacks
Since a stack is a list, any list implementation will do. Singly Linked List implementation of a stack: push by inserting at the front, pop by deleting the element at the front. Array implementation of stack: It is the more popular solution. It uses the InsertToBack and DeleteFromBack from the Vector implementation. Associated with each stack is Array and TopOfStack which is set to -1 for an empty stack. public class ArrayStack<AnyType> { private AnyType[] arr; private int top = -1; public ArrayStack(int capacity) { if (capacity <= 0) throw new IllegalArgumentException( “Capacity must be positive."); arr = (AnyType[]) new Object[capacity]; top = -1; } Izmir University of Economics
4
Array Implementation of Stacks - I
public boolean isEmpty() { return (top == -1); } public boolean isFull() { if (top == arr.length - 1) return true; return false; public void push(AnyType value) { if (isFull()) throw new StackException("Stack is full."); arr[++top] = value; public void pop() { if(isEmpty()) throw new StackException("Stack is empty."); top--; Izmir University of Economics
5
Array Implementation of Stacks - II
public AnyType Top( ){ /* TopAndPop is similar */ if (isEmpty()) throw new StackException("Stack is empty."); return arr[ top ]; } public AnyType TopAndPop() { return arr[ top-- ]; public class StackException extends RuntimeException{ public StackException(String message) { super(message); } /* end of ArrayStack<AnyType> */ Izmir University of Economics
6
Stack Applications - Balancing Symbols
Compilers check programs for syntax errors, but frequently a lack of one symbol (such as a missing brace or comment starter) will cause the compiler to spill out a hundred lines of diagnostics. Thus, every right brace, bracket, and parenthesis must correspond to their left counterparts. Example: The sequence [()] is legal, but [(]) is not. stack Ø; while (!eof(file)){ read(char); if (isOpening(char)) push(char, stack); else if (isClosing(char)) if (isEmpty(stack) error(); else cchar = topAndPop(stack); if (!isMatching(char,cchar)) } if (!isEmpty(stack)) It is clearly linear and actually makes only one pass through the input. It is thus on-line and quite fast. Izmir University of Economics
7
Stack Applications – Postfix Expressions
Order of evaluation for arithmetic expressions depending on the precedence and associativity of operators has a huge impact on the result of the evaluation. Example: * 1.06 = produces either 19.05, or Most simple four-function calculators will give the first answer, but better calculators know that multiplication has higher precedence than addition. A scientific calculator generally comes with parentheses, so we can always get the right answer by parenthesizing, but with a simple calculator we need to remember intermediate results. Izmir University of Economics
8
Izmir University of Economics
Postfix Notation (((a*b)+c)+(d*e)) fully parenthesized T1=a*b, T1=T1+c, T2=d*e, T1=T1+T2 by using intermediate results a b * c + d e * + is the equivalent of using intermediate results. This notation is known as postfix or reverse Polish notation. Notice that when an expression is given in postfix notation, there is no need to know any precedence rules. Izmir University of Economics
9
Postfix Expression Evaluation
* * First four symbols are placed on the stack. This algorithm depicted below is clearly O(N) + 8 * * 8 * * * * + 3 + * 3 + * + * * Izmir University of Economics
10
Infix to Postfix Conversion
We can use stacks to convert an expression in standart (also known as infix) form into postfix. Example: operators = {+, *, (, )}, We apply usual precedence rules; Infix: a + b * c + (d * e + f) * g Postfix: a b c * + d e * f + g * + Izmir University of Economics
11
Infix to Postfix - Algorithm
stack Ø; while (! eos(expr)){ read(char); if (isOperand(char)) output(char); else if (char == “)”) while ((!isEmpty(stack))&&((sc=topAndPop(stack))!= “(”)) output(sc); else while ( (!isEmpty(stack)) && inStackPriority(top(stack))>=(outStackPriority(char)))) output(topAndPop(stack)); push(char, stack); } while (!isEmpty(stack)) output(pop(stack)); inStackPriority outStackPriority ** (RL) 4 5 *, / (LR) 3 +, - (LR) 2 ( 1 6 inStackPriority(“(”)=very low outStackPriority(“(”)=very high Izmir University of Economics
12
Example I Example: Infix equation is (A+B/C*(D+E)-F). What is postfix version of it? Symbol Stack Postfix Priority: ^ , (*, / , %), (+,-) ( ( A ( A + ( + A B ( + A B / ( + / A B C ( + / A B C * ( + / * A B C / Pop the operator with higher or eq. Priority, so pop / ( ( + * ( A B C / D ( + * ( A B C / D + ( + * ( + A B C / D E ( + * ( + A B C / D E ) ( + * ( + ) A B C / D E Bracket closes pop + and remove parantheses - ( + * - A B C / D E + * Higher priority must come before lower, so pop * ( + - A B C / D E + * + Equal priority cannot stay together, so pop + F ( - A B C / D E + * + F ) ( - ) A B C / D E + * + F - Bracket closes pop - and remove ( and )
13
Infix to Postfix Using stack – Example 2
1: a + b * c + (d * e + f) * g 4: (d * e + f) * g 2: * c + (d * e + f) * g 5: * e + f) * g 3: + (d * e + f) * g Izmir University of Economics
14
Infix to Postfix Using stack – Example 2
6: + f) * g 8: * g 7: ) * g Izmir University of Economics
15
Izmir University of Economics
Function Calls The algorithm to check balanced symbols suggests a way to implement function calls. The problem here is that when a call is made to a new function, all the variables local to the calling routine need to be saved by the system. Furthermore, the current location in the routine must be saved so that the new function knows where to go after it is done. “(“ and “)” are exactly like function call and function return. Every PL implementing recursion has that mechanism. The information saved is called either an activation record or stack frame. There is always the possibility that you will run out of stack space by having too many simultaneously active functions. On many systems there is no checking for overflow. Izmir University of Economics
16
Function Calls and Recursion
The routine printList printing out collection, is perfectly legal and actually correct. It properly handles the base case of an empty collection, and the recursion is fine. Unfortunately, if the list contains 20,000 elements, there will be a stack of 20,000 activation records (and hence possibly a program crash). Izmir University of Economics
17
Eliminating Recursion
This is an example of an extremely bad use of recursion known as tail recursion (recursive call at the last line). It can be automatically eliminated by enclosing the body in a while loop and replacing the recursive call with one assignment per function argument. Izmir University of Economics
18
Izmir University of Economics
Homework Assignments 3.23, 3.24, 3.25.a, You are requested to study and solve the exercises. Note that these are for you to practice only. You are not to deliver the results to me. Izmir University of Economics
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.