CSC 1052 Stacks 1/11/2019.

Slides:



Advertisements
Similar presentations
Stacks & Their Applications COP Stacks  A stack is a data structure that stores information arranged like a stack.  We have seen stacks before.
Advertisements

Stacks Chapter 11.
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.
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.
Lecture 7 Sept 16 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
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.
Unit 11 1 Unit 11: Data Structures H We explore some simple techniques for organizing and managing information H This unit focuses on: Abstract Data Types.
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,
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.
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,
Stacks (Revised and expanded from CIT 591). What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on.
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 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. 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.
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.
Chapter 6 Stacks. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 6-2 Chapter Objectives Examine stack processing Define a stack abstract.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures Stacks.
Data Structures Using C++ 2E Chapter 7 Stacks. Data Structures Using C++ 2E2 Objectives Learn about stacks Examine various stack operations Learn how.
Topic 3 The Stack ADT.
Fundamentals of Python: From First Programs Through Data Structures Chapter 14 Linear Collections: Stacks.
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.
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.
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.
Data Structures and Algorithms
Mastering STACKS AN INTRODUCTION TO STACKS Data Structures.
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.
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.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
Stacks and Queues. 2 3 Runtime Efficiency efficiency: measure of computing resources used by code. can be relative to speed (time), memory (space), etc.
Chapter 12: Collections by Lewis and Loftus (Updated by Dan Fleck) Coming up: Collections.
11/24/ CSC Outline  Stacks  Basic operations  Examples of use  Queues  Basic operations  Examples of use  Implementations  Array-based.
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)
Data Structures & Algorithms
Lecture Objectives  To understand how Java implements a stack  To learn how to implement a stack using an underlying array or linked list  Implement.
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.
Click to edit Master text styles Stacks Data Structure.
Stacks and Queues. 2 Abstract Data Types (ADTs) abstract data type (ADT): A specification of a collection of data and the operations that can be performed.
Stacks Access is allowed only at one point of the structure, normally termed the top of the stack access to the most recently added item only Operations.
CS Data Structures Chapter 6 Stacks Mehmet H Gunes
Data Structures Using C++ 2E
Stacks Chapter 5.
Stacks Stacks.
Data Structures Interview / VIVA Questions and Answers
The Stack ADT. 3-2 Objectives Define a stack collection Use a stack to solve a problem Examine an array implementation of a stack.
Cinda Heeren / Geoffrey Tien
Copyright ©2012 by Pearson Education, Inc. All rights reserved
Stacks Chapter 4.
Data Structures – Week #3
Stack Data Structure, Reverse Polish Notation, Homework 7
Stacks Chapter 5 Adapted from Pearson Education, Inc.
Stacks and Queues.
Stacks.
Stacks.
Cs212: Data Structures Computer Science Department Lecture 6: Stacks.
Stacks.
Collections Framework
Stacks.
Introduction to Data Structure
Data Structures – Week #3
Chapter 7 (continued) © 2011 Pearson Addison-Wesley. All rights reserved.
Stacks and Queues.
Presented by : Aman Gupta PGT CS KV No.1, Narimedu, Madurai
CHAPTER 3: Collections—Stacks
Presentation transcript:

CSC 1052 Stacks 1/11/2019

Outline Stacks Basic operations Examples of use Queues Implementations Array-based and linked list-based 1/11/2019

Static vs. Dynamic Structures Recall that a static data structure has a fixed size This meaning is different from those associated with the static modifier. Arrays are static; once you define the number of elements it can hold, it doesn’t change. A dynamic data structure grows and shrinks as required by the information it contains.

Stacks A stack ADT is linear, like a list or queue, meaning that it maintains its information in a straight line. Items are added and removed from only one end of a stack. It is therefore LIFO: Last-In, First-Out. An Analogy: a stack of plates where the last plate on is the first on off the top.

Stacks Stacks are often drawn vertically: PUSH POP add remove

A conceptual view of a stack 1/11/2019

Stacks Some stack operations: - push -add an item to the top of the stack. - pop - remove an item from the top of the stack. - peek - retrieves top item without removing it. - empty - returns true if the stack is empty.

Stacks A stack is a structure of ordered items such that items can be inserted and removed only at one end - called the Top. A stack is a LIFO or Last-in/First-Out structure. Items are taken out of the stack in reverse order from their insertion. 1/11/2019

Non-Computer Examples Stack of papers Stack of bills Stack of plates Expect O ( 1 ) time per stack operation. (In other words, constant time per operation, no matter how many items are actually in the stack). 1/11/2019

Stack The stack specification lists a stack constructor and five methods. One of the simplest stack implementations is to reverse a word. Most compilers use stacks to analyze the syntax of a program. 1/11/2019

Using a Stack to reverse a word Input NAT Push T Using a Stack to reverse a word Push N Push A T A N A N N Pop T Pop A POP N Output TAN A N N 1/11/2019

STACKS applications At all times in the execution of the reverse word program, the only item that can accessed from the stack, is the item on TOP. We will use a method called peek() to view the top item Stacks are also used frequently to evaluate expressions so that will be the next application we will look at. 1/11/2019

Applications Stacks can be used to check a program for balanced symbols (such as {}, (), []). Example: {()} is legal, {(}) is not (so simply counting symbols does not work). When a closing symbol is seen, it must match the most recently seen unclosed opening symbol. Therefore, a stack will be appropriate. 1/11/2019

Balanced Symbol Algorithm Make an empty stack. Repeatedly read tokens(parenthesis); if the token is: an opening symbol, push it onto the stack If it is a closing symbol and the stack is empty, then report an error; otherwise pop the stack and verify that the popped symbol is a match (if not report an error) At the end of the file, if the stack is not empty, report an error. 1/11/2019

Example ( { { Input: { ( ) } Push { Push ( stack now has { ( Pop - Next comes a ) , pop an item, it is ( which matches ). Stack now has { Pop – Next comes a } , pop an item, it is { which matches }. End of file; stack is empty, so all is good. ( { { 1/11/2019

Input: ( { } { } ) { { ( ( ( Read 2nd }, pop matching { Read ) and Pop ( Read and Push ( Read and Push { Read first } , pop matching { Read and Push 2nd { Empty Stack { ( { ( ( ( ( 1/11/2019

Input: [ { } { } ]{} { And so on.. { [ [ [ 1 2 3 4 [ [ 5 6 Initial Empty Stack Read and Push [ Read and Push { Read first }, pop matching { { [ [ [ 1 2 3 4 Read and Push 2nd { Read 2nd }, pop matching { { And so on.. [ [ 5 6 1/11/2019

Performance Running time is O( N ), where N is amount of data (that is, number of tokens). Algorithm is online: it processes the input sequentially, never needing to backtrack. 1/11/2019

Balancing an expression In the method IsBalanced(String exp) an expression is checked to see if all the parentheses match. A charStack is set up whose legal characters are: “() {} [} “ A switch is used 1/11/2019

Method Stack Matching symbols is similar to method call and method return, because when a method returns, it returns to the to the method that called it. A method stack can be used to keep track of this. Abstract idea: when a method call is made, save current state on a stack. On return, restore the state by popping the stack. 1/11/2019

Stack Frames or Activation Records Programs compiled from modern high level languages make use of a stack frame for the working memory of each method invocation.   When any method is called, a number of words - the stack frame - is pushed onto a program stack. When the method returns, this frame of data is popped off the stack. 1/11/2019

Stack frame or Activation Record Frame contains: Method arguments Return address Local variables 1/11/2019

method f( int x, int y) { int a; if ( term_cond ) return …; a = … method f( int x, int y) { int a; if ( term_cond ) return …; a = ….; return g( a ); } method g( int z ) { int p, q; p = …. ; q = …. ; return f(p,q); } Context for execution of f: Each frame contains parameters, return address and local variables 1/11/2019

Activation Records As a method calls another method, first its arguments, then the return address and finally space for local variables is pushed onto the stack. Actual implementation is slightly different . The top of stack can store the current method environment. When method is called, the new environment is pushed onto stack. On return, the old environment is restored by popping the method environment. 1/11/2019

Stack Frames Ø Since each function runs in its own "environment" or context, it becomes possible for a function to call itself - a technique known as recursion. Ø This capability is extremely useful and extensively used - because many problems are elegantly specified or solved in a recursive way. 1/11/2019

Stack Frames The most common applications for stacks have a space restraint so that using an array implementation is a natural and efficient one. (In most operating systems, allocation and de-allocation of memory is a relatively expensive operation, there is a penalty for the flexibility of linked list implementations.). 1/11/2019

Array Implementations Stacks can be implemented with an array and an integer top that stores the array index of the top of the stack. Empty stack has top equal to -1. To push, increment the top counter, and write in the array position. To pop, decrement the top counter. 1/11/2019

Stages A B top(1) top(-1) A top(0) 1/11/2019

Array Doubling If the stack is full (because array size has been reached), we can extend the array, using array doubling. We allocate a new, double-sized array and copy contents over: TempArray =[T] new Object[ OldArray.length * 2 ]; for( int j = 0; j < OldArray.length; j++ ) TempArray[ j ] = OldArray[ j ]; OldArray = TempArray; 1/11/2019

Running Time Without array doubling, all operations are constant time, and do not depend on number of items in the stack. With array doubling, a push could occasionally be O( N ). However, if the array doubling occurs infrequently, it is essentially O( 1 ) because each array doubling that costs N assignments is preceded by N/2 non-doubling pushes. 1/11/2019

Expression Evaluation 1/11/2019

Examples 4-4-4 evaluates to -4 2^2^3 evaluates to 256 Parenthesis override precedence and associativity. Regular expressions can be changed into postfix and then solved. After the regular expression is changed to postfix it is easier to solve than directly solving and regular(infix) expression 1/11/2019

Postfix Expressions 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 onto the stack At the end, there will be one value on the stack, which is the value of the expression 1/11/2019

Postfix Example 1 2 3 * + Push 1, Push 2, Push 3. When * is seen, Pop 3, Pop 2, evaluate 2 * 3, and Push the result 6. When + is seen, Pop 6, Pop 1, evaluate 1 + 6, and Push the result 7. At end of expression, stack should have one item, which is the answer. 1/11/2019

Postfix Example, Continued The following operations will store the expression on the stack. As an operator is encountered the operators are popped and the appropriate operation performed. 1 2 3 * + 7 1 2 3 6 Push 1 Push 2 Push 3 Pop 3 Pop 2 Push 6 Pop 6 Pop 1 Push 7 1/11/2019

OLD COMPILERS translated infix expressions using two stacks into machine language. AN OPERATOR IS PLACED BETWEEN ITS OPERANDS c – d + (e * f – g * h) / i INFIX MACHINE LANGUAGE THIS GETS MESSY BECAUSE OF PARENTHESES and need for two stacks NEWER COMPILERS: INFIX POSTFIX MACHINE LANGUAGE 1/11/2019

IN POSTFIX NOTATION, AN OPERATOR IS PLACED IMMEDIATELY AFTER ITS OPERANDS. INFIX POSTFIX a + b ab+ a + b * c abc*+ a * b + c ab*c+ (a + b) * c ab+c* PARENTHESES NOT NEEDED – AND NOT USED – IN POSTFIX 1/11/2019

The LinkedStack Class Now let's examine a linked implementation of a stack We will reuse the LinearNode class that we used in LinkedList implementation to define the linked implementation of a set collection Internally, a stack is represented as a linked list of nodes, with a reference to the top of the stack and an integer count of the number of nodes in the stack 1/11/2019

A linked implementation of a stack 1/11/2019

LinkedStack - the push Operation 1/11/2019

The stack after pushing element E 1/11/2019

ArrayStack - the pop Operation 1/11/2019

The stack after a pop operation 1/11/2019

The ArrayStack Class Now let's examine an array-based implementation of a stack We'll make the following design decisions: maintain an array of T references the bottom of the stack is at index 0 the elements of the stack are in order and contiguous an integer variable top stores the index of the next available slot in the array This approach allows the stack to grow and shrink at the higher indexes 1/11/2019

An array implementation of a stack 1/11/2019

ArrayStack - the push Operation //----------------------------------------------------------------- // 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 (size() == stack.length) expandCapacity(); stack[top] = element; top++; } 1/11/2019

The stack after pushing element E 1/11/2019

ArrayStack - the pop Operation //----------------------------------------------------------------- // Removes the element at the top of the stack and returns a // reference to it. Throws an EmptyStackException if the stack // is empty. //----------------------------------------------------------------- public T pop() throws EmptyStackException { if (isEmpty()) throw new EmptyStackException(); top--; T result = stack[top]; stack[top] = null; return result; } 1/11/2019

The stack after popping the top element 1/11/2019

A UML description of the java.util.Stack class 1/11/2019

Analysis of Stack Operations Because stack operations all work on one end of the collection, they are generally efficient The push and pop operations, for both linked and array implementations, are O(1) Likewise, the other operations for all implementations are O(1) We'll see that other collections (which don't have that characteristic) aren't as efficient for all operations 1/11/2019

Collections Framework Let’s review more about the properties that all the collection classes have in common: Allow the collection size to increase dynamically All only hold items of class of generic T Provides at least two contructors – one to create an empty collection and one that accepts as a parameter any other collection object and creates a new collection object that holds the same information. 1/11/2019

Collections Framework The collections differ in: Logical structure of the elements they contain The underlying implementation’ The efficiency of the various operations The set of supported operations Whether they allow duplicates Whether they allow keys Whether the elements are sorted 1/11/2019

Collections Framework The Vector class has been replaced by the ArrayList class which provides the same methods in a single thread environment. The HashTable class also supports synchronization so for single thread programs you should use HashMap. The Stack class of the Collections Framework is implemented with a Vector. There are the expected problems with performance due to concurrency and a logical error. Vectors allow access anywhere in the array, stacks do not. 1/11/2019

Collections Framework The Collection Interface is used by classes that do not support a unique key value, e.g. unkeyed lists and sets. Some methods in the interface are: boolean Add(T obj) - adds obj to Collection boolean addAll(Collection c) –add c to Collection boolean contain(T obj) – return true if obj is in Collection boolean isEmpty() - returns true if collection is empty 1/11/2019

Collections Framework The MAP interface:: This interface is used by library collection classes that map unique keys to values. It defines a a method to retrieve an object based on its key value. Classes that implement the MAP interface are: AbstractMap, HashMap and HashTable. 1/11/2019

Collections Framework The AbstractCollection Class implements the Collection interface. The Collection interface defines 15 operations Some of these methods define fundamental operations which will vary with the particular collection. Others will be the same no matter what the implementation, e.g. The size method will depend upon the implementation so it is an abstract method but the isEmpty() method can be implemented as: public boolean isEmpty() { return (this.size() == 0) } 1/11/2019

Collections Framework By defining as many methods as possible in terms of the fundamental operations, the AbstractCollection class cuts down on the time to implement a new collection. In addition, two other abstract classes extend the AbstractCollection class – AbstractSet and AbstractList. Both these classes perform the same services as the AbstractCollection class Finally, concrete classes extend AbstractSet and AbstractList. 1/11/2019

1/11/2019