Topic 3 The Stack ADT.

Slides:



Advertisements
Similar presentations
CS Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.
Advertisements

Stacks.
Chapter 5 Queues Modified. Chapter Scope Queue processing Comparing queue implementations 5 - 2Java Software Structures, 4th Edition, Lewis/Chase.
Stacks Chapter 5. Chapter Objectives  To learn about the stack data type and how to use its four methods: push, pop, peek, and empty  To understand.
Topic 15 Implementing and Using Stacks
Stacks CS-240 Dick Steflik. Stacks Last In, First Out operation - LIFO As items are added they are chronologically ordered, items are removed in reverse.
Stacks Chapter 5. Chapter 5: Stacks2 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop, peek, and empty.
Introduction to Stacks What is a Stack Stack implementation using arrays. Application of Stack.
Stacks.
Chapter 3 Collections. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 3-2 Chapter Objectives Define the concept and terminology related.
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,
1 Lecture 24 Abstract Data Types (ADT) –I Overview  What is an Abstract Data type?  What is Stack ADT?  Stack ADT Specifications  Array Implementation.
CHAPTER 3 COLLECTIONS SET Collection. 2 Abstract Data Types A data type consists of a set of values or elements, called its domain, and a set of operators.
Stacks. 2 What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
Stacks. 2 Outline and Reading The Stack ADT (§2.1.1) Array-based implementation (§2.1.1) Growable array-based stack (§1.5) Java.util.Stack class Java.util.Vector.
Part-B1 Stacks. Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations.
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.
Stacks. 2 Outline and Reading The Stack ADT (§2.1.1) Applications of Stacks (§2.1.1) Array-based implementation (§2.1.1) Growable array-based stack (§1.5)
CHAPTER 6 Stacks. 2 A stack is a linear collection whose elements are added and removed from one end The last element to be put on the stack is the first.
TCSS 342, Winter 2005 Lecture Notes
Chapter 6 Stacks. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 6-2 Chapter Objectives Examine stack processing Define a stack abstract.
Chapter 12 Introduction to Collections - Stacks
Data Structures Using C++ 2E Chapter 7 Stacks. Data Structures Using C++ 2E2 Objectives Learn about stacks Examine various stack operations Learn how.
Abstract Data Types (ADTs) and data structures: terminology and definitions A type is a collection of values. For example, the boolean type consists of.
Exam 1 –Monday June 25 th –open Book / Open Notes –No Electronic Devices (calculators, laptops, etc) –Room Number: W –Time: 5:30pm to 8:00pm.
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.
1 CSC 222: Computer Programming II Spring 2005 Stacks and recursion  stack ADT  push, pop, peek, empty, size  ArrayList-based implementation, java.util.Stack.
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
Lecture Objectives To understand how Java implements a stack To learn how to implement a stack using an underlying array or linked list Implement a simple.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Chapter 3 Introduction to Collections – Stacks Modified
Chapter 4 Stacks Stacks A stack is a linear data structure that can be accessed only at one of its ends for storing and retrieving. Its called.
SAK 3117 Data Structures Chapter 3: STACKS. Objective To introduce: Stack concepts Stack operations Stack applications CONTENT 3.1 Introduction 3.2 Stack.
DATA STRUCTURE & ALGORITHMS CHAPTER 3: STACKS. 2 Objectives In this chapter, you will: Learn about stacks Examine various stack operations Discover stack.
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)
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
Chapter 7 Stacks. © 2004 Pearson Addison-Wesley. All rights reserved 7-2 The Abstract Data Type: Developing an ADT During the Design of a Solution Specifications.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 3: Collections Java Software Structures: Designing and Using.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
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.
30 May Stacks (5.1) CSE 2011 Winter Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 6 Stacks. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine stack processing Define a stack abstract.
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)
Chapter 2 Collections. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Define the concept and terminology related.
Collections Chapter 12 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
1 Stacks (Continued) and Queues Array Stack Implementation Linked Stack Implementation The java.util.Stack class Queue Abstract Data Type (ADT) Queue ADT.
Lecture Objectives  To understand how Java implements a stack  To learn how to implement a stack using an underlying array or linked list  Implement.
Collections Using Generics in Collections. 2 Chapter Objectives Define the concept and terminology related to collections Explore the basic structure.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
Click to edit Master text styles Stacks Data Structure.
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.
1 Stacks Abstract Data Types (ADTs) Stacks Application to the analysis of a time series Java implementation of a stack Interfaces and exceptions.
Collections & Stacks Collections A collection is an object that holds and organizes other objects It provides operations for accessing and managing.
Stacks Stack Abstract Data Type (ADT) Stack ADT Interface
Stack: a Linked Implementation
Data Structures Using C++ 2E
Stacks.
The Stack ADT. 3-2 Objectives Define a stack collection Use a stack to solve a problem Examine an array implementation of a stack.
Chapter 3 Introduction to Collections - Stacks
Java Software Structures: John Lewis & Joseph Chase
Stacks.
Stacks.
CSC 1052 Stacks 1/11/2019.
Cs212: Data Structures Computer Science Department Lecture 6: Stacks.
Stacks.
Stacks.
CHAPTER 3: Collections—Stacks
Presentation transcript:

Topic 3 The Stack ADT

Objectives Define a stack collection Use a stack to solve a problem Examine an array implementation of a stack

Stacks Stack : a collection whose elements are added and removed from one end, called the top of the stack Stack is a LIFO ( last in, first out ) data structure Examples: A stack of plates – what can we do with the elements of this collection? Other real-world examples of stacks? Can add a plate to the top, take a plate form the top, look at the top plate Can check if the stack is empty. We do not take a plate from the middle of the pile! (usually) So, where is all the activity for a stack of plates?

Conceptual View of a Stack Adding an element New object is added as the new top element of the stack (old) top of stack new top bottom of stack bottom

Conceptual View of a Stack Removing an element Object is removed from the top of the stack top new top bottom bottom

Uses of Stacks in Computing Useful for any kind of problem involving LIFO data Backtracking: in puzzles and games Browsers To keep track of pages visited in a browser tab

Uses of Stacks in Computing Word Processors, editors To check expressions or strings of text for matching parentheses / brackets e.g. if (a == b) { c = (d + e) * f; } To implement undo operations Keeps track of the most recent operations Markup languages (e.g. HTML, XML): have formatting information (tags) as well as raw text To check for matching tags e.g. <HEAD> <TITLE>Computer Science 1027a</TITLE> </HEAD>

Uses of Stacks in Computing Stack Calculators To convert an infix expression to postfix, to make evaluation easier (more on this later) Infix expression: a * b + c Postfix expression: a b * c + To evaluate postfix expressions (ditto) Compilers To convert infix expressions to postfix, to make translation of a high-level language such as Java or C to a lower level language easier

Uses of Stacks in Computing Call stack (Runtime stack) Used by runtime system when methods are invoked, for method call / return processing (more on this later) e.g. main calls method1 method1 calls method 2 method 2 returns … Holds “call frame” containing local variables, parameters, etc. Why is a stack structure used for this?

Operations on a Collection Every collection has a set of operations that define how we interact with it, for example: Add elements Remove elements Determine if the collection is empty Determine the collection's size 10

Stack Operations push: add an element at the top of the stack pop: remove the element at the top of the stack peek: examine the element at the top of the stack It is not legal to access any element other than the one that is at the top of the stack!

Operations on a Stack Operation Description push pop peek isEmpty size Adds an element to the top of the stack pop Removes an element from the top of the stack peek Examines the element at the top of the stack isEmpty Determines whether the stack is empty size Determines the number of elements in the stack toString Returns a string representation of the stack

Discussion Do the operations defined for the stack have anything to do with Java? Do they say what the stack is used for? Do they say how the stack is stored in a computer? Do they say how the operations are implemented?

Stack ADT Stack Abstract Data Type (Stack ADT) It is a collection of data Together with the operations on that data We just discussed the operations We will now formally define the interface of the collection Recall that the interface of the collection tells us what we need to know in order to interact with it, i.e. what the operations are

Java Interfaces Java has a programming construct called an interface that we use to formally define what the operations on a collection are in Java Java interface: a list of abstract methods and constants Must be public Constants must be declared as final static

Java Interfaces Abstract method : a method that does not have an implementation, i.e. it just consists of the header of the method: return type method name (parameter list)

Java Interface for Stack ADT public interface StackADT<T> { // Adds one element to the top of this stack public void push (T element); // Removes and returns the top element from this stack public T pop( ); // Returns without removing the top element of this stack public T peek( ); // Returns true if this stack contains no elements public boolean isEmpty( ); // Returns the number of elements in this stack public int size( ); // Returns a string representation of this stack public String toString( ); }

Generic Types What is this <T> in the interface definition? It represents a generic type For generality, we can define a class (or interface) based on a generic type rather than an actual type Example: we define a Stack for objects of type T The actual type is known only when an application program creates an object of that class Examples: in a card game: a Stack of Card objects in checking HTML tags: a Stack of Tag objects

Generic Types Note: it is merely a convention to use T to represent the generic type In the class definition, we enclose the generic type in angle brackets: < T >

Implementing an Interface One or more classes can implement an interface, perhaps differently A class implements the interface by providing the implementations (bodies) for each of the abstract methods Uses the reserved word implements followed by the interface name We will see Stack ADT implementation examples soon … but first we will look at using a stack

Using a Stack: Postfix Expressions Normally, we write expressions using infix notation: Operators are between operands: 3 + 4 * 2 Parentheses force precedence: (3 + 4) * 2 In a postfix expression, the operator comes after its two operands Examples above would be written as: 3 4 2 * + 3 4 + 2 * What is the advantage of writing expressions in postfix form?

Evaluating Postfix Expressions Algorithm to evaluate a postfix expression: Scan from left to right, determining if the next token is an operator or operand If it is an operand, push it on the stack If it is an operator, pop the stack twice to get the two operands, perform the operation, and push the result back onto the stack Try the algorithm on our examples … At the end, there will be one value on the stack – what is it?

Using a Stack to Evaluate a Postfix Expression Evaluation of 7 4 -3 * 1 5 + / * top top 5 top -3 1 6 top top 4 -12 -12 -12 -2 top 7 7 7 7 7 -14 4 * -3 1 + 5 -12 / 6 7 * -2 At end of evaluation, the result is the only item on the stack

Java Code to Evaluate Postfix Expressions For simplicity, assume the operands in the expressions are integer literals See Postfix.java Reads postfix expressions and evaluates them See PostfixEvaluator.java The postfix expression evaluator Note that it uses a class called ArrayStack, which is an implementation of the Stack ADT that we will now examine We will see later that it could just as well have used a different implementation of the Stack ADT!

Implementing a Stack Does an application program need to know how the Stack collection is implemented? No - we are using the Stack collection for its functionality (what); how it is implemented is not relevant The Stack collection could be implemented in various ways; let’s first examine how we can use an array of references to objects

An Array of Object References 1 2 3 4 5 6

Stack Implementation Issues What do we need to implement a stack? A data structure (container) to hold the data elements Something to indicate the top of the stack

Array Implementation of a Stack Our container will be an array to hold the data elements Data elements are kept contiguously at one end of the array The top of the stack will be indicated by its position in the array (index) Let’s assume that the bottom of the stack is at index 0 The top of the stack will be represented by an integer variable that is the index of the next available slot in the array

Array Implementation of a Stack A Stack s with 4 elements 1 2 3 4 5 6 7 … ? ? ? ? s stack 4 top After pushing an element 1 2 3 4 5 6 7 … ? ? ? s stack 5 top

. … . . … After popping one element 1 2 3 4 5 6 7 ? ? ? stack s 4 top 1 2 3 4 5 6 7 . … ? ? ? stack s 4 top After popping a second element 1 2 3 4 5 6 7 . . … ? ? ? stack s 3 top

Java Implementation The array variable stack holds references to objects Their type is determined when the stack is instantiated The integer variable top stores the index of the next available slot in the array What else does top represent? The number of elements currently in the stack!

The ArrayStack Class The class ArrayStack implements the StackADT interface: public class ArrayStack<T> implements StackADT<T> In the Java Collections API, class names indicate both the underlying data structure and the collection We will adopt the same naming convention: the ArrayStack class represents an array implementation of a stack collection

ArrayStack Data Fields Attributes (instance variables): private T[ ] stack; // the container for the data private int top; // indicates the next open slot Note that these were not specified in the Java interface for the StackADT (why not?) There is also a private constant (see later) private final int DEFAULT_CAPACITY=100;

ArrayStack constructors //----------------------------------------------------------------- // Creates an empty stack using the default capacity. public ArrayStack( ) { top = 0; stack = (T[ ]) (new Object[DEFAULT_CAPACITY]); } // Creates an empty stack using the specified capacity. public ArrayStack (int initialCapacity) stack = (T[ ]) (new Object[initialCapacity]); ArrayStack constructors

ArrayStack Constructors Note: constructors are not specified in the Java interface for the StackADT (why not?) What is the purpose of (T[ ]) ? The elements of the stack array are of generic type T Recall: we can’t instantiate anything of a generic type So, we need to instantiate an element of type Object and cast it into the type T Specifically, we are casting an array of Object objects into an array of type T

Example of using Constructor to create a Stack of Numbers What happens in memory when an ArrayStack object is created using the following statement? ArrayStack<Integer> s = new ArrayStack<Integer>(5); top Technically, the instance variables lie inside the stack object, but the array referenced by stack lies outside it s stack ? ? ? ? ? 1 2 3 4

Example: the same ArrayStack object after four items have been pushed on top 56 17 4 s stack 2 4 ? 1 3 41 32

The push( ) operation Where in the array is the element added? //----------------------------------------------------------------- // Adds the specified element to the top of the stack, // expanding the capacity of the stack array if necessary public void push (T element) { if (top == stack.length) expandCapacity( ); stack[top] = element; top++; } The push( ) operation Where in the array is the element added?

Managing Capacity An array has a particular number of cells when it is created (its capacity), so the array's capacity is also the stack's capacity What happens when we want to push a new element onto a stack that is full, i.e. add it to an array that is at capacity? The push method could throw an exception It could return some kind of status indicator (e.g. a boolean value true or false, that indicates whether the push was successful or not) It could automatically expand the capacity of the array

Discussion What are the implications to the class using the stack, of each of the three solutions?

The expandCapacity( ) helper method //----------------------------------------------------------------- // Helper method to create a new array to store the // contents of the stack, with twice the capacity private void expandCapacity( ) { T[ ] larger = (T[ ]) (new Object[stack.length*2]); for (int index=0; index < stack.length; index++) larger[index] = stack[index]; stack = larger; } The expandCapacity( ) helper method

//----------------------------------------------------------------- // Removes the element at the top of the stack and returns a // reference to it. Throws an EmptyCollectionException if the // stack is empty. public T pop( ) throws EmptyCollectionException { if (isEmpty( )) throw new EmptyCollectionException(“Stack” ); top--; T result = stack[top]; stack[top] = null; return result; } The pop( ) operation Note the order: decrement top before getting element from array (why?)

Stack Exceptions What happens if the user of the Stack collection attempts to pop an element from an empty stack? The designer of the implementation determines how it will be handled: The user of the stack could check beforehand, using the isEmpty method Here, the pop method throws an exception if the stack is empty In this case the user of the stack can deal with the problem (using a try/catch)

The toString( ) operation //----------------------------------------------------------------- // Returns a string representation of this stack. public String toString( ) { String result = ""; for (int index=0; index < top; index++) result = result + stack[index].toString( ) + "\n"; return result; } The toString( ) operation

The isEmpty( ) operation //----------------------------------------------------------------- // Returns the number of elements in the stack public int size( ) { return top; } // Returns true if the stack is empty and false otherwise public boolean isEmpty( ) return (top == 0); The size( ) operation The isEmpty( ) operation

Exercise Fill in the code for the peek operation on the next slide

//----------------------------------------------------------------- // Returns a reference to the element at the top of the stack. // The element is not removed from the stack. // Throws an EmptyCollectionException if the stack is empty. public T peek( ) throws EmptyCollectionException { } The peek( ) operation

Discussion At any point, how many elements are there on the stack? Where does the stack grow and shrink? What is the advantage of having the bottom (rather than the top) of the stack be at index 0 ? What happens when the stack is empty? Can the stack be full?

The java.util.Stack Class The Java Collections API contains an implementation of a Stack class with similar operations It has some additional operations (e.g. search, which returns distance from top of stack) Stack class is derived from the Vector class, which has a dynamically “growable” array So it has some characteristics that are not appropriate for a pure stack (e.g. inherited method to add item in middle)