SAK 3117 Data Structures Chapter 3: STACKS. Objective To introduce: Stack concepts Stack operations Stack applications CONTENT 3.1 Introduction 3.2 Stack.

Slides:



Advertisements
Similar presentations
Stacks Chapter 11.
Advertisements

Stacks - 3 Nour El-Kadri CSI Evaluating arithmetic expressions Stack-based algorithms are used for syntactical analysis (parsing). For example.
COSC 2006 Chapter 7 Stacks III
C o n f i d e n t i a l Developed By Nitendra NextHome Subject Name: Data Structure Using C Title : Overview of Stack.
E.G.M. Petrakisstacks, queues1 Stacks  Stack: restricted variant of list  elements may by inserted or deleted from only one end : LIFO lists  top: the.
Infix to postfix conversion Process the tokens from a vector infixVect of tokens (strings) of an infix expression one by one When the token is an operand.
Infix, Postfix, Prefix.
Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,
Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
1 Introduction to Stacks What is a Stack? Stack implementation using array. Stack implementation using linked list. Applications of Stacks.
Topic 15 Implementing and Using Stacks
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures Stacks.
More About Stacks: Stack Applications Dan Nguyen CS 146, Spring 2004 Professor Sin-Min Lee.
The Stack and Queue Types Lecture 10 Hartmut Kaiser
Objectives of these slides:
Topic 3 The Stack ADT.
Ceng-112 Data Structures ITurgut Kalfaoglu 1 Chapter 3 Stacks.
Data Structures Lecture : Stacks (Infix, Postfix and Prefix Expressions) Azhar Maqsood NUST Institute of Information Technology (NIIT)
Comp 245 Data Structures Stacks. What is a Stack? A LIFO (last in, first out) structure Access (storage or retrieval) may only take place at the TOP NO.
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
Data Structures: CSCI 362 – Stack Implementation Data Structures: CSCI 362 – Stack Implementation lecture notes adapted from Data Structures with C++ using.
Stack Applications.
1 Stacks Chapter 4 2 Introduction Consider a program to model a switching yard –Has main line and siding –Cars may be shunted, removed at any time.
1 Stacks – Chapter 3 A stack is a data structure in which all insertions and deletions of entries are made at one end, called the top of the stack. Alternatively,
Week7 Stack Data Structures & Algorithms. Introduction to Stacks and Queues Widely used data structures Ordered List of element Easy to implement Easy.
CSC 205 Programming II Postfix Expressions. Recap: Stack Stack features Orderly linear structure Access from one side only – top item Stack operations.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Computer Science Department Data Structure & Algorithms Problem Solving with Stack.
Data Structures. The Stack: Definition A stack is an ordered collection of items into which new items may be inserted and from which items may be deleted.
DATA STRUCTURE & ALGORITHMS CHAPTER 3: STACKS. 2 Objectives In this chapter, you will: Learn about stacks Examine various stack operations Discover stack.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Stacks 1. Stack  What is a stack? An ordered list where insertions and deletions occur at one end called the top. Also known as last-in-first-out (LIFO)
Stacks  Introduction  Applications  Implementations  Complex Applications.
Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.
EC-211 DATA STRUCTURES LECTURE 8. STACK APPLICATIONS Infix, Prefix, and Postfix Expressions Example – Infix: A+B – Prefix: +AB – Postfix: AB+
For more notes and topics VISIT: IMPLEMENTATION OF STACKS eITnotes.com.
CHAPTER 3 STACK CSEB324 DATA STRUCTURES & ALGORITHM.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 19: Stacks and Queues (part 2)
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 18: Stacks and Queues (part 2)
Stacks An Abstract Data Type. Restricted Access Unlike arrays, stacks only allow the top most item to be accessed at any time The interface of a stack.
Copyright © Curt Hill Stacks An Useful Abstract Data Type.
CHP-3 STACKS.
Stacks A stack is a linear data structure that can be accessed only at one of its ends for storing and retrieving data LIFO (Last In First Out) structure.
Data Structures: A Pseudocode Approach with C1 Chapter 3 Objectives Upon completion you will be able to Explain the design, use, and operation of a stack.
1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks.
CC 215 DATA STRUCTURES MORE ABOUT STACK APPLICATIONS Dr. Manal Helal - Fall 2014 Lecture 6 AASTMT Engineering and Technology College 1.
Stacks Chapter 3 Objectives Upon completion you will be able to
Applications of Stack Maitrayee Mukerji. Stacks Last In First Out (LIFO List) ◦ FILO? Insertions and Deletions from the same end called the Top Push(),
1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks.
Stacks Stacks.
Stacks Chapter 7 introduces the stack data type.
The Stack ADT. 3-2 Objectives Define a stack collection Use a stack to solve a problem Examine an array implementation of a stack.
Copyright ©2012 by Pearson Education, Inc. All rights reserved
Stacks Chapter 4.
Stack application: postponing data usage
Algorithms and Data Structures
STACK CHAPTER 03 Developed By :- Misha Ann Alexander Data Structures.
Visit for more Learning Resources
PART II STACK APPLICATIONS
COMPUTER 2430 Object Oriented Programming and Data Structures I
Stacks Chapter 5 Adapted from Pearson Education, Inc.
More About Stacks: Stack Applications
COMPUTER 2430 Object Oriented Programming and Data Structures I
Stacks.
(Part 2) Infix, Prefix & Postfix
More About Stacks: Stack Applications
Data Structures and Algorithms 2/2561
Stacks A stack is an ordered set of elements, for which only the last element placed into the stack is accessible. The stack data type is also known as.
Presentation transcript:

SAK 3117 Data Structures Chapter 3: STACKS

Objective To introduce: Stack concepts Stack operations Stack applications CONTENT 3.1 Introduction 3.2 Stack using Array-Based Implementation 3.3 Stack Application: Postponing Data Usage Infix To Postfix Transformation Evaluating Postfix Expressions

3.1 Introduction Stack is a linear list in which data items can only be accessed at one end, called the top of the stack. Last-In–First-Out (LIFO) concept. Fig. 1: Stack

3.1 Introduction Data item: Simple data types. Stack applications classified into 4 broad categories: Reversing data – e.g. reverse a list & convert decimal to binary. Eg. 26 = Parsing data – e.g. translate a source program to machine language. Postponing data usage – e.g. evaluation, transformation. Backtracking – e.g. computer gaming, decision analysis, expert systems.

3.1 Introduction Basic operations: Peek – if the stack is not empty, return its top element. Pop – if the stack is not empty, delete and return its top element. Push – add a given element to the top of the stack. Fig. 2: Push stack operation

3.1 Introduction Size – return the number of elements in the stack. Pop – remove the top element of the stack and return it to the user. Fig. 3: Pop stack operation

3.1 Introduction Peek – copies the element at the top of the stack; return the data in the top element to the user but does not delete it. Fig. 4: Peek operation Fig. 3: Pop stack operation

3.1 Introduction Example: Given stack S with list of operations as below. Illustrate the stack operations step by step: S.push (green), S.push (blue), S.pop( ), S.push(red), topItem = S.peek( ), S.pop( ), S.pop( )

3.2 STACK USING ARRAY- BASED IMPLEMENTATION Declarations of data structure and functions prototype for Stack operations in a Header File. > Stack +peek() Object +pop() Object +push(Object) +size() int

3.2 STACK USING ARRAY- BASED IMPLEMENTATION A Stack Interface: 1 /** 2 * The Stack interface specifies the basic operations 3 * of a last-in-first-out (LIFO) containers. 4 */ 5 public interface Stack { 6 7 /** 8 * Returns a reference to the top element on this stack, leaving 9 * the stack unchanged. 10 * 11 the element at the top of this stack. 12 IllegalStateException if this stack is empty. 13 */ 14 public Object peek(); /** 17 * Removes and returns the element at the top of this stack. 18 * 19 the element at the top of this stack. 20 IllegalStateException if this stack is empty. 21 */ 22 public Object pop(); /** 25 * Adds the specified element to the top of this stack. 26 * 27 object the element to be pushed onto this stack. 28 */ 29 public void push(Object object); /** 32 * Returns the number of elements in this stack. 33 * 34 the number of elements in this queue. 35 */ 36 public int size(); 37 }

3.2 STACK USING ARRAY- BASED IMPLEMENTATION  The implementation file begins as follows: > Stack +peek() Object +pop() Object +push(Object) +size() int ArrayStack - a: Object[] - size int (methods)

3.2 STACK USING ARRAY- BASED IMPLEMENTATION An ArrayStack Class public class ArrayStack implements Stack { private Object[] a; private int size; }  The implementations of the class’s member functions are included at this point in the implementation file. Fig. 6: Conceptual & physical stack implementation

3.2 STACK USING ARRAY- BASED IMPLEMENTATION Create Stack Create stack initialize the stack pointer (i.e. top) to NULL, this indicates top as the new empty stack. Function definition: public ArrayStack(int capacity) { a = new Object[capacity]; } Empty Stack Check if stack is empty. Function definition: public boolean isEmpty() { return (size == 0); }

3.2 STACK USING ARRAY- BASED IMPLEMENTATION Push Adds an item at the top of the stack. If there is not enough space to insert - overflow state. public void push(Object object) { if (size == a.length) resize(); a[size++] = object; }

3.2 STACK USING ARRAY- BASED IMPLEMENTATION Pop // retrieves and removes the top of a stack public Object pop() { if (size == 0) throw new IllegalStateException("stack is empty"); Object object = a[--size]; a[size] = null; return object; }

3.2 STACK USING ARRAY- BASED IMPLEMENTATION Peek Function definition: public Object peek() { if (size == 0) throw new IllegalStateException("stack is empty"); return a[size-1]; }

3.2 STACK USING ARRAY- BASED IMPLEMENTATION  Resize an array private void resize() { Object[] aa = a; a = new Object[2*aa.length]; System.arraycopy(aa, 0, a, 0, size); }

3.2 STACK USING ARRAY- BASED IMPLEMENTATION Implementation: Public class Test ArrayStack { public static void main (String[] args) { Stack crates = new ArrayStack(4); crates.push(“CARROTS”); crates.push(“ORANGES”); crates.push(“RAISINS”); crates.push(“PICKLES”); crates.push(“BANANAS”); System.out.println(“crates.size(): “ + crates.size() + “\tcrates.peek(): “ + crates.peek()); System.out.println(“crates.pop(): “ + crates.pop()); System.out.println(“crates.size(): “ + crates.size() + “\tcrates.peek(): “ + crates.peek()); crates.push(“WALNUTS”); crates.push(“OYSTERS”); System.out.println(“crates.size(): “ + crates.size() + “\tcrates.peek(): “ + crates.peek()); System.out.println(“crates.pop(): “ + crates.pop()); }

3.2 STACK USING ARRAY- BASED IMPLEMENTATION Output: crates.size(): 5 crates.peek(): BANANAS crates.pop(): BANANAS crates.pop(): PICKLES crates.pop(): RAISINS crates.size(): 2 crates.peek(): ORANGES crates.size(): 4 crates.peek(): OYSTERS crates.pop(): OYSTERS crates.pop(): WALNUTS crates.pop(): ORANGES crates.pop(): CARROTS java.lang.IllegalStateException: stack is empty Exception in thread main

3.3 STACK APPLICATION: POSTPONING DATA USAGE ARITHMETIC STATEMENT Example: A * B + C (How computers generate it???) Arithmetic expression written in INFIX as above example. However compiler change to POSTFIX/PREFIX for calculating purposes. Three different formats: Infix: A + B the operator comes between two operands. Prefix: +AB the operator comes before the two operands. Postfix: AB+ the operator comes after its two operands.

3.3 STACK APPLICATION: POSTPONING DATA USAGE How to convert INFIX expression to POSTFIX and PREFIX? Example: To calculate INFIX expression requires priority like ()*/ etc whereas POSTFIX and PREFIX are not. Evaluate postfix expression – Stack Example: Infix form: * Convert to postfix:2 5 3 * + 1 – INFIXPREFIXPOSTFIX A+B*C (A+B)/(C-D) (A+B)*C A/B-C/D A+B-C*D

3.3 STACK APPLICATION: POSTPONING DATA USAGE ARITHMETIC STATEMENT 1. Initialize an empty stack. 2. Repeat the following until the end of the expression is encountered: 2.1 Get next token (/constant, variable, arithmetic operator) in the postfix expression. 2.2If token is an operand, push it onto the stack. If it is an operator, then i.Pop top two values from the stack. If stack does not contain two items, error due to a malformed postfix. Evaluation terminated. ii.Apply the operator to these two values. iii.Push the resulting value back onto the stack.

3.3 STACK APPLICATION: POSTPONING DATA USAGE ARITHMETIC STATEMENT 1. Initialize an empty stack. 2. Repeat the following until the end of the expression is encountered: 2.1 Get next token (/constant, variable, arithmetic operator) in the postfix expression. 2.2If token is an operand, push it onto the stack. If it is an operator, then i. Pop top two values from the stack. If stack does not contain two items, error due to a malformed postfix. Evaluation terminated. ii. Apply the operator to these two values. iii. Push the resulting value back onto the stack. 3. When the end of expression encountered, its value is on top of the stack (and, in fact, must be the only value in the stack). TRY THIS: * + 1 – ? Example: Using Stack Interface defined above.

3.3 STACK APPLICATION: POSTPONING DATA USAGE public static void main(String[] args) { char ch; Stack s; // create stack double operan1, operan2, value; System.out.println( “Type postfix expression: “); while ( ch = System.in.read() && ch != ‘\n’) { if ( Character.isDigit(ch) ) s.push(ch – 48); else { s.pop(operan2); s.pop(operan1); switch (ch) { case ‘+’ : s.push(operan1+operan2); break; case ‘-’ : s.push(operan1-operan2); break; case ‘*’ : s.push(operan1*operan2); break; case ‘/’ : s.push(operan1+operan2); break; } // end switch } // end else } //end while s.pop(value); System.out.println(“ = “ + value); }

3.3 STACK APPLICATION: POSTPONING DATA USAGE Below is the output: 73/ 345*+ = * = *5+ = *++ = */7+ = 10.00

3.3 STACK APPLICATION: POSTPONING DATA USAGE CONVERT INFIX TO POSTFIX EXPRESSION Example: * 3 ? 1. Start scan from left to right. Copy operand 7 to output expression. Push operand + into stack. Output Stack

3.3 STACK APPLICATION: POSTPONING DATA USAGE 2. Copy operand 2 to output expression. Ensure that 2 is the right operand for the previous operator or left operand for the next operator. Compare operators’ priority. Because the priority of * is higher than + then push operator * into stack. Output Stack

3.3 STACK APPLICATION: POSTPONING DATA USAGE 3. Copy operand 3 to output expression. Output Stack 4. End Scan. Copy all the operator from stack to output expression. Output * +

3.3 STACK APPLICATION: POSTPONING DATA USAGE  Algorithm: Convert infix to postfix 1. Read infix expression as input. 2. If input is operand, output the operand. 3. If input is an operator +, -, *, /, then pop and output all operators of >= precedence. Push operator. 4. If input is (, then push. 5. If input is ), then pop and output all operators until you see a ( on the stack. Pop the ( without output. 6. If no more input then pop and output all operators on stack.

3.3 STACK APPLICATION: POSTPONING DATA USAGE  Hierarchy of operator priority: OperatorStackInput )0 ( * /43

3.3 STACK APPLICATION: POSTPONING DATA USAGE  Example: 2 * 3 + (4 - 2) convert to Postfix OutputStackDescription

3.3 STACK APPLICATION: POSTPONING DATA USAGE  Converting Expression from Infix to Prefix using STACK It is a bit trickier algorithm, in this algorithm we first reverse the input expression so that a+b*c will become c*b+a and then we do the conversion and then again the output string is reversed. Doing this has an advantage that except for some minor modifications the algorithm for Infix->Prefix remains almost same as the one for Infix- >Postfix.  Algorithm 1. Reverse the input string. 2. Examine the next element in the input. 3. If it is operand, add it to output string. 4. If it is Closing parenthesis, push it on stack

3.3 STACK APPLICATION: POSTPONING DATA USAGE 5. If it is an operator, then i.If stack is empty, push operator on stack. ii.If the top of stack is closing parenthesis, push operator on stack. iii.If it has same or higher priority than the top of stack, push operator on stack. iv.Else pop the operator from the stack and add it to output string, repeat step If it is a opening parenthesis, pop operators from stack and add them to output string until a closing parenthesis is encountered. Pop and discard the closing parenthesis. 7. If there is more input go to step 2 8. If there is no more input, pop the remaining operators and add them to output string. 9. Reverse the output string.

3.3 STACK APPLICATION: POSTPONING DATA USAGE  Example Suppose we want to convert 2*3/(2-1)+5*(4-1) into Prefix form: Reversed Expression: )1-4(*5+)1-2(/3*2 Char Scanned Stack Contents(Top on right) Prefix Expression(right to left) ) ) 1 ) 1 - )- 1 4 )- 14 ( Empty 14- * * * * ) +) 14-5* 1 +) 14-5*1 - +)- 14-5*1 2 +)- 14-5*12 ( *12- / +/ 14-5* / 14-5*12-3 * +/* 14-5* /* 14-5*12-32 Empty 14-5*12-32*/+ Reverse the output string : +/*23-21*5-41 So, the final Prefix Expression is +/*23-21*5-41

3.3 STACK APPLICATION: POSTPONING DATA USAGE  Exercises 1.Convert the following infix expressions to postfix expressions using the algorithmic method (a stack diagram): a) A + B * ( C – D ) / ( E – F ) b) (A – B + C * ( D + E ) ) / F c) A * ( B + C / ( D – E ) ) 2.Using the algorithmic method (a stack diagram) evaluate the following postfix expressions when the variables have the following values A is 2, B is 3, C is 4, and D is 5. a) A B * C – D + b) A B C + * D –