Stacks

CMPUT 175 Introduction to Foundations of Computing

  • Instructor: Osmar R. Zaïane, University of Alberta

  • Date: January 29, 2025

  • Topic: Stacks and Abstract Data Types

Objectives

  • Understand linear data structures: Stacks, Queues, and Deques

  • Learn how to implement these structures in Python

  • Explore useful applications of these data structures

Abstract Data Types (ADT)

  • ADT: A formal description independent of programming language

  • Implementation of data structure and behavior must remain consistent through interfaces

  • Changes in implementation should not affect code that relies on a consistent interface

Linear Structures

  • Linear Structure: A non-indexed container that grows/shrinks one element at a time

  • Key features:

    • Two ends (Front and Rear or Top and Bottom)

    • Containers differ in the location of item addition/removal

  • Common examples: Lists, Stacks, Queues, Deques, Trees, Heaps, Binary Search Trees, B-Trees, Maps, Graphs

Stacks

  • Stack definition: A collection accessed only via the last inserted element (Last In - First Out - LIFO)

  • Operations:

    • Push: Add element to the stack

    • Pop: Remove the top element from the stack

    • Peek: View the top element without removing it

    • isEmpty: Check if the stack has elements

    • Size: Get the number of items in the stack

Applications of Stacks

  • Reversing sequences: Use LIFO to reverse a sequence by pushing and popping elements

  • Navigating web pages: Browsers use stacks to track history for the back button using push/pop operations

  • Maze traversal: Use of a stack to hold unsearched paths for exploring mazes

  • Matching parenthesis: Verification of correctly matched groups of parentheses using a stack

Implementation of Stack in Python

  • Creating a Stack class:

    • Initialize an empty list to store items

    • Implement methods for push, pop, peek, isEmpty, and size

Example Implementation 1

class Stack:
    def __init__(self):
        self.items = []

    def push(self, item):
        self.items.insert(0, item)

    def pop(self):
        return self.items.pop(0)

    def peek(self):
        return self.items[0]

    def isEmpty(self):
        return self.items == []

    def size(self):
        return len(self.items)

Example Implementation 2

  • Implementing with the stack's top as the end of a list

class Stack:
    def __init__(self):
        self.items = []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        return self.items.pop()

    def peek(self):
        return self.items[-1]

    def isEmpty(self):
        return self.items == []

    def size(self):
        return len(self.items)

Performance and Comparison

  • Performance evaluation of stack implementations using timeit module

  • Both implementations should yield similar results, as the behavior remains consistent despite differences in structure

Expression Evaluation Through Stacks

  • Infix, Prefix, Postfix: Understand these expressions and their precedence

  • Stack usage in converting expressions from infix to postfix

    • Follow rules for handling operators and parentheses when appending to output lists

Python Implementation for Infix to Postfix

def infixToPostfix(infixexpr):  
    alphaOperand="ABCDEFGHIJKLMNOPQRSTUVWXYZ"  
    digitOperand="0123456789"  
    prec = {  
        "*": 3,  
        "/": 3,  
        "+": 2,  
        "-": 2,  
        "(": 1  
    }  
    opStack = Stack()  
    postfixList = []  
    tokenList = infixexpr.split()  
    for token in tokenList:  
        if token in alphaOperand or token in digitOperand:  
            postfixList.append(token)  
        elif token == '(':  
            opStack.push(token)  
        elif token == ')':  
            topToken = opStack.pop()  
            while topToken != '(':  
                postfixList.append(topToken)  
                topToken = opStack.pop()  
        else:  
            while (not opStack.isEmpty()) and\
                    (prec[opStack.peek()] >= prec[token]):  
                postfixList.append(opStack.pop())  
            opStack.push(token)  
    while not opStack.isEmpty():  
        postfixList.append(opStack.pop())  
    return " ".join(postfixList)

Conclusion

  • The efficiency of using stacks for various computing tasks, such as expression evaluation and matching parentheses, is highlighted.

  • Proper encapsulation allows for flexibility in data structure implementations.