0% found this document useful (0 votes)
35 views27 pages

CSC310 Ch07

s.pop() b c Removes and returns the top item c s.pop() a b Removes and returns the top item b s.pop() blank a Removes and returns the last item a s.isEmpty() blank True Checks if the stack is empty This chapter discusses stacks, which are linear data structures that follow a last-in, first-out (LIFO) approach. Stacks have push and pop operations to add and remove elements from the top. The chapter covers stack implementations, applications, and interfaces in Python including using lists to emulate stacks.

Uploaded by

apord211
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views27 pages

CSC310 Ch07

s.pop() b c Removes and returns the top item c s.pop() a b Removes and returns the top item b s.pop() blank a Removes and returns the last item a s.isEmpty() blank True Checks if the stack is empty This chapter discusses stacks, which are linear data structures that follow a last-in, first-out (LIFO) approach. Stacks have push and pop operations to add and remove elements from the top. The chapter covers stack implementations, applications, and interfaces in Python including using lists to emulate stacks.

Uploaded by

apord211
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Chapter 7: Stacks

Fundamentals of Python: Data Structures, Second Edition

Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as
permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Learning Objectives

• Describe the features and behavior of a stack


• Choose a stack implementation based on its performance
characteristics
• Explain how the system call stack provides run-time support for
recursive subroutines

Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted
in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Overview of Stacks (1 of 3)

• Stacks – linear collections


• Access is completely restricted to just one end called the top
• Use a last-in-first-out (LIFO) protocol
• Analogy
• Stack of clean trays in a cafeteria
• New tray is removed from top of the stack, when needed
• Operations for putting items on and removing items from a stack are
called push and pop

Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted
in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Overview of Stacks (2 of 3)

Figure 7-1: Some states in the lifetime of a stack

Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted
in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Overview of Stacks (3 of 3)

• Applications of stacks in computer science


• Translating infix expressions to postfix form and evaluating postfix
expressions
• Backtracking algorithms
• Managing computer memory in support of function and method
calls
• Supporting the undo feature in text editors, word processors,
spreadsheet programs, drawing programs, and similar applications
• Maintaining a history of the links visited by a web browser

Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted
in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Using a Stack

• A stack type is not built into Python


• Programmers can use a Python list to emulate an array-based stack:
• The list method append pushes an element onto this stack
• The list method pop removes and returns the element at its top
• The main drawback of this option is as follows:
• All other list operations can manipulate the stack as well

Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted
in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
The Stack Interface (1 of 5)

• A stack interface provides an operation named peek for examining


the element at the top of a stack
• The stack type can also include operations such as
• clear, isEmpty, len, str, in, and +
• These operations are listed as Python methods in Table 7.1 (see next
slide)

Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted
in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
The Stack Interface (2 of 5)

• Table 7.1 The Methods in the Stack Interface

Stack Method What It Does

s.isEmpty() Returns True if s is empty or False otherwise.

s._len_() Same as len(s). Returns the number of items in s.

s._str_() Same as str(s). Returns the string representation of s.

Same as iter(s), or for item in s:. Visits each item


s._iter_()
in s, from bottom to top.
Same as item in s. Returns True if item is in s or
s._contains.(item)
False otherwise.
Same as s1 + s2. Returns a new stack containing the
s1._add_(s2)
items in s1 and s2.

Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted
in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
The Stack Interface (3 of 5)

• Table 7.1 The Methods in the Stack Interface (continued)

Stack Method What It Does

s._eq_(anyObject) Same as s==anyObject.

s.clear() Makes s become empty.

Returns the item at the top of s. Precondition: s must not


s.peek()
be empty; raises a KeyError if the stack is empty.
s.push(item) Adds item to the top of s.

Removes and returns the item at the top of s.


s.pop() Precondition: s must not be empty; raises a KeyError if
the stack is empty.

Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted
in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
The Stack Interface (4 of 5)

• Table 7.2 The Effect of Stack Operations

State of Stack after the


Operation Value Returned Comment
Operation
s = <Stack Initially, stack is
blank blank
Type> () empty.
The stack contains the
s.push (a) a blank
single item.
s.push (b) ab blank b is the top item.

s.push (c) abc blank c is the top item.

The stack is not


s.isEmpty () abc False
empty.
The stack contains
len (s) abc 3
three items.
Return the top item
s.peek () abc c
without removing it.
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted
in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
The Stack Interface (5 of 5)

• Table 7.2 The Effect of Stack Operations (continued)


State of Stack after
Operation Value Returned Comment
the Operation
Remove and return the top
s.pop () ab c
item. b is now the top item.
Remove and return the top
s.pop () a b
item. a is now the top item.
Remove and return the top
s.pop () blank a
item.
s.isEmpty () blank True The stack is empty.

Peeking at an empty stack


s.peek () blank KeyError
raises an exception.
Popping an empty stack
s.pop () blank KeyError
raises an exception.
s.push (d) D blank d is the top item.

Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted
in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Instantiating a Stack

• Later in this chapter, two different implementations are considered:


• ArrayStack
• LinkedStack
• This code segment shows how you might instantiate them:
• s1=ArrayStack ()
• s2=LinkedStack ([20, 40, 60])

Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted
in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Implementations of Stacks

• Stacks are implemented easily using arrays or linked structures


• The following sections show that there are trade-offs involved in using
these two recurring approaches

Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted
in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Test Driver

• Two stack implementations are the classes ArrayStack and


LinkedStack
• Before you develop these, write a short tester program that shows how
you can test them immediately
• The code in this program exercises all the methods in any stack
implementation and gives you an initial sense that they are working as
expected:
• See the text for the code along with the output

Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted
in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Adding Stacks to the Collection Hierarchy (1 of 2)

• ArrayStack and LinkedStack


• Implement the same interface, called StackInterface
• Are subclasses of the AbstractStack class, which in turn is a subclass of
AbstractCollection
• Inherit the add method from the AbstractStack class, the size variable,
and the methods isEmpty, __len__, __str__, __add__, and
__eq__ from AbstractCollection
• The only methods that need to be implemented in ArrayStack and
LinkedStack are _init_, peek, push, pop, clear,
and _iter_

Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted
in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Adding Stacks to the Collection Hierarchy (2 of 2)

Figure 7-5: The stack resources in the collection hierarchy

Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted
in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Array Implementation

• The first implementation is built around an array called self.items


and an integer called self.size
• Figure 7.6 shows how self.items and self.size appear when
four items are on the stacks
• Figure 7-6: An array representation of a stack with four items

Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted
in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Linked Implementation (1 of 4)

• The linked implementation requires two classes:


• LinkedStack and Node
• The Node class contains two fields:
• data — An item on the stack
• next — A pointer to the next node
• Because new items are added to and removed from just one end of the
linked structure, the methods pop and push are easy to implement, as
shown in Figures 7.8 and 7.9

Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted
in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Linked Implementation (2 of 4)

Figure 7-8: Pushing an


item onto a linked stack

Figure 7-9: Popping an


item from a linked stack

Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted
in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Linked Implementation (3 of 4)

• Code for LinkedStack:


from node import Node
from abstractstack import AbstractStack

class LinkedStack(AbstractStack):
""" Link-based stack implementation."""

def __init__(self, sourceCollection = None):


self.items = None
AbstractStack.__init__(self, sourceCollection)

# Accessors
def __iter__(self):
"""Supports iteration over a view of self.
Visits items from bottom to top of stack."""
def visitNodes(node):
if node != None:
visitNodes(node.next)
tempList.append(node.data)
tempList = list()
visitNodes(self.items)
return iter(tempList)

def peek(self):
"""Returns the item at top of the stack.
Precondition: the stack is not empty."""
if self.isEmpty():
raise KeyError("The stack is empty.")
return self.items.data

Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted
in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Linked Implementation (4 of 4)

• Code for LinkedStack (continued):


# Mutators
def clear(self):
"""Makes self become empty."""
self.size = 0
self.items = None

def push(self, item):


"""Inserts item at top of the stack."""
self.items = Node(item, self.items)
self.size += 1

def pop(self):
"""Removes and returns the item at top of the stack.
Precondition: the stack is not empty."""
if self.isEmpty():
raise KeyError("The stack is empty.")
oldItem = self.items.data
self.items = self.items.next
self.size -= 1
return oldItem

Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted
in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
The Role of the Abstract Stack Class (1 of 2)

• The __init__ method in AbstractCollection uses the


add method to add items in a source collection to self:
• If self is a stack, Python raises an exception, stating that the add method is
undefined for stacks
• To remedy this problem and maintain consistency with the interfaces
of other collections,
• You need to include an add method with your stack types
• The logical place to put this method, so that all stack types can use it, is in the
AbstractStack class

Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted
in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
The Role of the Abstract Stack Class (2 of 2)

• Code for AbstractStack:


"""
File: abstractstack.py
Author: Ken Lambert
"""

from abstractcollection import AbstractCollection

class AbstractStack(AbstractCollection):
"""An abstract stack implementation."""

# Constructor
def __init__(self, sourceCollection):
"""Sets the initial state of self, which includes the
contents of sourceCollection, if it's present."""
AbstractCollection.__init__(self, sourceCollection)

# Mutator methods
def add(self, item):
"""Adds item to self."""
self.push(item)

Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted
in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Time and Space Analysis of the Two
Implementations (1 of 2)

• With the exception of the __iter__ method,


• All the stack methods are simple and have a maximum running time of O(1), or
constant
• In the array implementation, the analysis becomes more complex:
• At the moment of doubling, the push method’s running time jumps to O(n), or
linear, but the rest of the time it remains at O(1)
• Similar remarks can be made about the pop method
• On average, both are still O(1)
• The recursive function used in the linked implementation causes a
linear growth of memory because of its use of the system call stack:
• Avoid this problem by using a doubly linked structure; the iterator can begin at
the last node and follow links to previous nodes
Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted
in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Time and Space Analysis of the Two
Implementations (2 of 2)

• A linked stack of n items requires n nodes, each containing two


references:
• One to an item and the other to the next node
• In addition, there must be a variable that points to the top node and a variable
for the size, yielding a total space requirement of 2n + 2
• For an array implementation,
• Assuming that an integer and a reference occupy the same amount of space, the
total space requirement is the array’s capacity + 2

• An array implementation is more space-efficient than a linked 1


2
implementation whenever the load factor is greater than

Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted
in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Chapter Summary (1 of 2)

• A stack is a linear collection that allows access to one end only, called
the top:
• Elements are pushed onto the top or popped from it
• Other operations on stacks include peeking at the top element,
determining the number of elements, determining whether the stack is
empty, and returning a string representation
• Stacks are used in applications that manage data items in a last-in-first-
out manner
• These applications include the following:
• Matching bracket symbols in expressions, evaluating postfix expressions,
backtracking algorithms, and managing memory for subroutine calls on a virtual
machine

Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted
in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.
Chapter Summary (2 of 2)

• Arrays and singly linked structures support simple implementations of


stacks

Fundamentals of Python: Data Structures, Second Edition. © 2019 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted
in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use.

You might also like