Computer Science 112 Fundamentals of Programming II Introduction to Stacks.

Slides:



Advertisements
Similar presentations
Stack & Queues COP 3502.
Advertisements

Computer Science 112 Fundamentals of Programming II Queues and Priority Queues.
Computer Science 112 Fundamentals of Programming II Overview of Collections.
Recursion vs. Iteration The original Lisp language was truly a functional language: –Everything was expressed as functions –No local variables –No iteration.
Stacks Chapter 11.
Computer Science 112 Fundamentals of Programming II Applications of Stacks.
COSC 2006 Chapter 7 Stacks III
COMPSCI 105 S Principles of Computer Science 13 Stacks.
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.
CMPT 225 Stacks-part2.
CMPT 225 Stacks.
© 2006 Pearson Addison-Wesley. All rights reserved7 B-1 Chapter 7 (continued) Stacks.
© 2006 Pearson Addison-Wesley. All rights reserved7A-1 Chapter 7 Stacks.
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.
Run time vs. Compile time
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.
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. © 2005 Pearson Addison-Wesley. All rights reserved6-2 The Abstract Data Type Specifications of an abstract data type for a particular.
Chapter 6 Stacks. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 6-2 Chapter Objectives Examine stack processing Define a stack abstract.
Digression: the “Stack” 1 CS502 Spring 2006 Digression: the “Stack” Imagine the following program:– int factorial(int n){ if (n
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures Stacks.
The Stack and Queue Types Lecture 10 Hartmut Kaiser
Data Structures Using C++ 2E Chapter 7 Stacks. Data Structures Using C++ 2E2 Objectives Learn about stacks Examine various stack operations Learn how.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 6: Stacks Data Abstraction & Problem Solving with C++
© 2006 Pearson Addison-Wesley. All rights reserved7A-1 Chapter 7 Stacks.
© 2006 Pearson Addison-Wesley. All rights reserved7A-1 Chapter 7 Stacks (and a bit of generics for flavor)
Topic 3 The Stack ADT.
Ceng-112 Data Structures ITurgut Kalfaoglu 1 Chapter 3 Stacks.
Fundamentals of Python: From First Programs Through Data Structures Chapter 14 Linear Collections: Stacks.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Data Structures and Algorithms
Review 1 Introduction Representation of Linear Array In Memory Operations on linear Arrays Traverse Insert Delete Example.
Chapter 7 Stacks I CS Data Structures I COSC 2006 April 22, 2017
Stacks & Recursion. Stack pushpop LIFO list - only top element is visible top.
Mastering STACKS AN INTRODUCTION TO STACKS Data Structures.
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.
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,
Computer Science 112 Fundamentals of Programming II Binary Search Trees.
Min Chen School of Computer Science and Engineering Seoul National University Data Structure: Chapter 3.
Chapter 6 B Stacks. © 2004 Pearson Addison-Wesley. All rights reserved6 B-2 Comparing Implementations All of the three implementations are ultimately.
Data Structures & Algorithms
Stacks Nour El-Kadri CSI Stacks Software stacks are abstract data types (structures) similar to physical stacks, Plates Trays Books PEZ dispenser.
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.
ITI Introduction to Computing II Lab-5 Dewan Tanvir Ahmed University of Ottawa.
CSC 205 – Java Programming II Lecture 30 April 3, 2002.
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.
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.
CC 215 DATA STRUCTURES MORE ABOUT STACK APPLICATIONS Dr. Manal Helal - Fall 2014 Lecture 6 AASTMT Engineering and Technology College 1.
CSC 143 P 1 CSC 143 Recursion [Chapter 5]. CSC 143 P 2 Recursion  A recursive definition is one which is defined in terms of itself  Example:  Compound.
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.
Chapter 6 A Stacks. © 2004 Pearson Addison-Wesley. All rights reserved6 A-2 The Abstract Data Type: Developing an ADT During the Design of a Solution.
CS Data Structures Chapter 6 Stacks Mehmet H Gunes
COSC160: Data Structures: Lists and Queues
Revised based on textbook author’s notes.
Fundamentals of Programming II Binary Search Trees
Homework 4 questions???.
COMPSCI 107 Computer Science Fundamentals
The Stack ADT. 3-2 Objectives Define a stack collection Use a stack to solve a problem Examine an array implementation of a stack.
Fundamentals of Programming II Backtracking with Stacks
CSC 205 – Java Programming II
Stacks.
Stacks.
Last Class We Covered Recursion Stacks Parts of a recursive function:
Data Structures and Algorithms 2/2561
Chapter 7 (continued) © 2011 Pearson Addison-Wesley. All rights reserved.
Presentation transcript:

Computer Science 112 Fundamentals of Programming II Introduction to Stacks

The Stack Collection: Overview Formal properties Applications Implementations

Formal Properties of Stacks Stacks are like lists in that elements are ordered by position (linear) However, access is only at one end, called the top A stack enforces last-in, first-out (LIFO) access

LIFO Access DDDDDDD push DDD pop Top of stack

s.isEmpty()Returns True if empty, False otherwise len(s)Returns the number of items in the stack str(s)Returns a string representation iter(s)Supports a for loop item in sTrue if item is in stack, False otherwise s1 + s2Returns a new stack with items in s1 and s2 s1 == s2Equality test for two stacks Minimal Set of Stack Operations

s.isEmpty()Returns True if empty, False otherwise len(s)Returns the number of items in the stack str(s)Returns a string representation iter(s)Supports a for loop item in sTrue if item is in stack, False otherwise s1 + s2Returns a new stack with items in s1 and s2 s1 == s2Equality test for two stacks s.push(item)Adds item to the top of the stack s.pop()Removes and returns top item s.peek()Returns item at the top of the stack The precondition of pop and peek is that the stack is not empty. Minimal Set of Stack Operations

Stack Implementations Array-based Singly linked structure Always a single set of abstract operations stack1 = LinkedStack() stack2 = ArrayStack([1, 2, 3, 4])

The Stack Resources LinkedStackArrayStack StackInterface AbstractStack AbstractCollection

stack = LinkedStack() # or ArrayStack() stack.push("A string") stack.push("Another string") for item in stack: print(item) while not stack.isEmpty(): print(stack.pop()) Example Use of a Stack We have a single set of abstract operations and two implementing classes, ArrayStack and LinkedStack

The Stack Iterator stack1 = LinkedStack([1, 2, 3, 4]) stack2 = ArrayStack(stack1) for item in stack1: print(item) for item in stack2: print(item) stack3 = ArrayStack(stack2) Does the iterator start at the top or the bottom of the stack?

Stack Applications Stacks are useful for algorithms that must backtrack to the most recent data element in a series of elements –Run-time support of recursion –Language processing –Game playing, puzzle solving –Tree and graph traversals

Example: N! N! = 1, when N = 1 N! = N * (N - 1)!, otherwise Recursive definition: def factorial(n): if n == 1: return 1 else: return n * factorial(n – 1) Recursive function: factorial(4) -> 4 * factorial(3) -> 3 * factorial(2) -> 2 * factorial(1) -> 1 <- 2 <- 6 <- 24 <- Runtime trace:

How Recursion Works Each call of a function generates an instance of that function An instance of a function contains –memory for each parameter –memory for each local variable –memory for the return value –a pointer to the caller ’ s next instruction (return address) This chunk of memory is also called an activation record

Example: factorial(4) 4 n return value Activation record for factorial(4) def factorial(n): if n == 1: return 1 else: return n * factorial(n – 1)

Activations Are Added Dynamically 4 n return value Activation record for factorial(4) 3 n return value Activation record for factorial(3) def factorial(n): if n == 1: return 1 else: return n * factorial(n – 1)

Number of Activations = # Calls 4 n return value Activation record for factorial(4) 3 n return value Activation record for factorial(3) 2 n return value Activation record for factorial(2) def factorial(n): if n == 1: return 1 else: return n * factorial(n – 1)

Recursive Process Bottoms out 4 n return value Activation record for factorial(4) 3 n return value Activation record for factorial(3) 2 n return value Activation record for factorial(2) 1 n return value Activation record for factorial(1) def factorial(n): if n == 1: return 1

Recursive Process Unwinds 4 n return value Activation record for factorial(4) 3 n return value Activation record for factorial(3) 2 n return value Activation record for factorial(2) 11 n return value Activation record for factorial(1) def factorial(n): if n == 1: return 1

Activations Are Deallocated 4 n return value Activation record for factorial(4) 3 n return value Activation record for factorial(3) 22 n return value Activation record for factorial(2) def factorial(n): if n == 1: return 1 else: return n * factorial(n – 1)

Activations Are Deallocated 4 n return value Activation record for factorial(4) 36 n return value Activation record for factorial(3) def factorial(n): if n == 1: return 1 else: return n * factorial(n – 1)

Value Returned Is in the First Activation 424 n return value Activation record for factorial(4) def factorial(n): if n == 1: return 1 else: return n * factorial(n – 1)

def factorialWithLoopAndStack(n): stack = LinkedStack() Loop with Explicit Stack

def factorialWithLoopAndStack(n): stack = LinkedStack() # Load up the stack with the sequence of numbers from n # down to 1. while n >= 1: stack.push(n) n -= 1 Loop with Explicit Stack

def factorialWithLoopAndStack(n): stack = LinkedStack() # Load up the stack with the sequence of numbers from n # down to 1. while n >= 1: stack.push(n) n -= 1 # Pop the top two numbers and push their product onto the # stack, until there is just one number left on the stack. while len(stack) > 1: operand1 = stack.pop() operand2 = stack.pop() product = operand1 * operand2 stack.push(product) Loop with Explicit Stack

def factorialWithLoopAndStack(n): stack = LinkedStack() # Load up the stack with the sequence of numbers from n # down to 1. while n >= 1: stack.push(n) n -= 1 # Pop the top two numbers and push their product onto the # stack, until there is just one number left on the stack. while len(stack) > 1: operand1 = stack.pop() operand2 = stack.pop() product = operand1 * operand2 stack.push(product) # Return the number at the top of the stack. return stack.peek() Loop with Explicit Stack

Matching Parentheses expression = { letter } | "(" expression ")" a ab (a) ((a)) (a(b)c) () (()) a( )( a) ((()) Grammar: Legal expressions: Illegal expressions: An expression is either a sequence of zero or more letters or an expression within parentheses.

Create a new stack Set match to true For each character in the string If the character equals '(' Push the character onto the stack Else If the character equals ')' If the stack is empty Set match to false Break Else Pop the top '(' from the stack If the stack is not empty Set match to false Return match Parentheses Matching Algorithm

def inputOk(s): stack = LinkedStack() match = True for ch in s: if ch == '(': stack.push(ch) elif ch == ')': if stack.isEmpty(): # No matching ( match = False break else: stack.pop() if not stack.isEmpty(): # No matching ) match = False return match Python Code

For Monday More stack applications