Abstract Data Types: Stacks and Queues

User-Defined Data Abstractions and Tagged Data

Abstract Data Types (ADTs) separate the interface of a data structure from its underlying implementation. By establishing a clear barrier between interface and implementation, programs become modular, easier to maintain, and less prone to errors.

Tagged data uses explicit symbols (such as string literals or identifiers) to label data structures. A tag acts as a runtime type marker that clearly indicates the category of object being handled.

Advantages of Tagged Data
  • Determining Object Types: Tags allow procedures to examine an incoming object and determine its specific abstraction type at runtime.

  • Data-Directed Programming: Using tags allows programs to inspect the type tag and dynamically dispatch execution to the appropriate procedure specialized for that type.

  • Defensive Programming: Tags facilitate defensive programming by validating input types prior to executing any state modifications or operations. If an argument does not match the expected tag, the system can fail gracefully by issuing descriptive errors rather than producing corrupted state or undefined behavior.


The Queue ADT (First-In, First-Out)

A Queue operates on a First-In, First-Out (FIFO) ordering discipline: the first element added to the collection is always the first element removed.

FIFO queue diagram illustrating enqueue at the back and dequeue at the front
Computational Applications
  • Graph Traversal: Breadth-first search (BFS) algorithms rely on queues to process graph vertices in order of increasing distance from the root.

  • Game Playing: Queues assist search strategies like iterative deepening.

  • Event Handling: Operating systems and GUI frameworks use event queues to process incoming user and hardware events in the exact sequence in which they occur.

Formal Interface Signatures

The Queue ADT comprises five standard operations:

  • Constructor:   makeQueue:void→Queue\text{makeQueue}: \text{void} \rightarrow \text{Queue}

  • Mutators:   enqueue:(Queue⟨A⟩,A)→void\text{enqueue}: (\text{Queue}\langle A \rangle, A) \rightarrow \text{void}   dequeue:Queue⟨A⟩→void\text{dequeue}: \text{Queue}\langle A \rangle \rightarrow \text{void}

  • Selector:   front:Queue⟨A⟩→A\text{front}: \text{Queue}\langle A \rangle \rightarrow A

  • Predicate:   isQueueEmpty:Queue⟨A⟩→Bool\text{isQueueEmpty}: \text{Queue}\langle A \rangle \rightarrow \text{Bool}

Conceptual REPL Walkthrough
>>> q = makeQueue()
>>> enqueue(q, 3)
>>> enqueue(q, 4)
>>> enqueue(q, 7)
>>> front(q)
3
>>> dequeue(q)
>>> front(q)
4

Queue Implementation Using Tagged Lists

Implementing an ADT requires selecting an underlying data representation and implementing every interface operation. The choice made for the constructor directly influences the design of mutators, selectors, and predicates.

For a mutable queue, the chosen internal representation is a tagged two-element tuple:

('queue', contents_list)
  • Element 00 is the string tag 'queue', identifying the data structure.

  • Element 11 is a mutable Python list representing the internal elements.

  • Because elements are inserted at one end and removed from the opposite end, enqueue and dequeue operations map directly to opposite ends of the internal list.

Base Constructor and Helper Procedures
def makeQueue():
    return ('queue', [])

def isQueue(obj):
    return type(obj) == type(()) and obj[0] == 'queue'

def contents(q):
    return q[1]
Primary Strategy: Enqueue at Back, Dequeue at Front

In this convention, new elements are appended to the end (back) of the list, and elements are popped from index 00 (front).

The Mutator enqueue

Basic version:

def enqueue(q, el):
    contents(q).append(el)

Defensive / safe version:

def enqueue(q, el):
    # adding to the back
    if isQueue(q):
        contents(q).append(el)
    else:
        # raise TypeError, "enqueue : Not a Queue"
        return TypeError(q, "enqueue : Not a Queue")
The Mutator dequeue

Basic version:

def dequeue(q):
    contents(q).pop(0)

Defensive / safe version:

def dequeue(q):
    # removing from front
    if not isQueueEmpty(q):
        contents(q).pop(0)
    else:
        raise IndexError("Queue is Empty")
The Selector front

Basic version:

def front(q):
    return contents(q)[0]

Defensive / safe version:

def front(q):
    if isQueue(q) and not isQueueEmpty(q):
        return contents(q)[0]
    else:
        raise TypeError("dequeue: arg must be a queue")
The Predicate isQueueEmpty

Basic version:

def isQueueEmpty(q):
    return contents(q) == []

Defensive / safe version:

def isQueueEmpty(q):
    if isQueue(q):
        return contents(q) == []
    else:
        raise TypeError("arg must be a queue")
Alternative Valid Strategy: Enqueue at Front, Dequeue at Back

An alternative valid implementation inserts new elements at index 00 and removes elements from the end using pop() and index −1-1:

def enqueue(q, el):
    # adding to the back
    if isQueue(q):
        contents(q).insert(0, el)
    else:
        return TypeError(q, "enqueue : Not a Queue")

def dequeue(q):
    # removing from front
    if not isQueueEmpty(q):
        contents(q).pop()
    else:
        raise IndexError("Queue is Empty")

def front(q):
    if isQueue(q) and not isQueueEmpty(q):
        return contents(q)[-1]
    else:
        raise TypeError("dequeue: arg must be a queue")
Mutable Queue in Action
>>> q = makeQueue()
>>> enqueue(q, 5)
>>> enqueue(q, 3)
>>> enqueue(q, 7)
>>> q
('queue', [5, 3, 7])
>>> front(q)
5
>>> dequeue(q)
>>> front(q)
3
>>> q
('queue', [3, 7])
>>> q = enqueue(q, 13)
>>> q

Note on mutator return values: Because enqueue is a mutator designed to modify the underlying data structure in place, assigning its return value (q = enqueue(q, 13)) overwrites the variable q with None if enqueue completes without an explicit return.


The Stack ADT (Last-In, First-Out)

A Stack operates on a Last-In, First-Out (LIFO) ordering discipline: the most recently added item is the first one to be removed.

Computational Applications
  • Recursion Management: Call stacks track function activation frames, parameter bindings, and return addresses.

  • Parsing: Compilers and interpreters use stacks to parse nested grammatical structures, syntax trees, and matching delimiters.

  • Graph Traversal: Depth-first search (DFS) uses a stack (explicitly or via system call stack recursion) to explore vertices along each branch before backtracking.

  • Game Tree Search: Used for backtracking and evaluating game search paths.

Formal Interface Signatures

The Stack ADT comprises five standard operations:

  • Constructor:   makeStack:void→Stack\text{makeStack}: \text{void} \rightarrow \text{Stack}

  • Mutators:   push:(Stack⟨A⟩,A)→void\text{push}: (\text{Stack}\langle A \rangle, A) \rightarrow \text{void}   pop:Stack⟨A⟩→void\text{pop}: \text{Stack}\langle A \rangle \rightarrow \text{void}

  • Selector:   top:Stack⟨A⟩→A\text{top}: \text{Stack}\langle A \rangle \rightarrow A

  • Predicate:   isStackEmpty:Stack⟨A⟩→Bool\text{isStackEmpty}: \text{Stack}\langle A \rangle \rightarrow \text{Bool}

Conceptual REPL Walkthrough
>>> s = makeStack()
>>> push(s, 3)
>>> push(s, 5)
>>> push(s, 7)
>>> top(s)
7
>>> pop(s)
>>> top(s)
5

Stack Implementation Using Tagged Lists

A mutable stack is represented as a tagged two-element tuple:

('stack', contents_list)
  • Element 00 is the tag 'stack' identifying the structure.

  • Element 11 is a mutable Python list containing the elements.

Implementation Choices: Top Location

A primary implementation choice is whether the top of the stack corresponds to the front (index 00) or the back (index −1-1) of the internal list. That choice constrains how push, pop, and top must be implemented.

Stack Operation

Top at Front (index 0)

Top at Back (index -1)

push(s, el)

contents(s).insert(0, el)

contents(s).append(el)

pop(s)

contents(s).pop(0)

contents(s).pop()

top(s)

return contents(s)[0]

return contents(s)[-1]

Base Constructor and Predicate Definitions
def makeStack():
    return ('stack', [])

def contents(s):
    return s[1]

def isStack(obj):
    return type(obj) == type(()) and obj[0] == 'stack'
Safe Implementations with Defensive Type Checking
The Predicate isStackEmpty

Basic version:

def isStackEmpty(s):
    return contents(s) == []

Safe version:

def isStackEmpty(s):
    if isStack(s):
        return contents(s) == []
    else:
        raise TypeError("isStackEmpty: arg must be a stack")
The Mutator push

Basic version:

def push(s, el):
    contents(s).insert(0, el)

Safe version:

def push(s, el):
    if isStack(s):
        contents(s).insert(0, el)
    else:
        raise TypeError("push: First arg must be a stack")
The Mutator pop

Basic version:

def pop(s):
    contents(s).pop(0)

Safe version:

def pop(s):
    if isStack(s) and not isStackEmpty(s):
        contents(s).pop(0)
    else:
        raise TypeError("pop: arg must be a stack")
The Selector top

Basic version:

def top(s):
    return contents(s)[0]

Safe version:

def top(s):
    if isStack(s) and not isStackEmpty(s):
        return contents(s)[0]
    else:
        raise TypeError("top: arg must be a stack")
Mutable Stack in Action
>>> s1 = makeStack()
>>> push(s1, 5)
>>> push(s1, 3)
>>> push(s1, 7)
>>> s1
('stack', [7, 3, 5])
>>> top(s1)
7
>>> pop(s1)
>>> top(s1)
3
>>> s1
('stack', [3, 5])

Aliasing and Mutation in Abstract Data Types

When working with mutable abstract data types, aliasing occurs when two or more distinct variable names refer to the exact same mutable object in memory.

Demonstration of Aliasing
>>> s1 = makeStack()
>>> push(s1, 3)
>>> push(s1, 5)
>>> s2 = s1
>>> top(s1)
5
>>> top(s2)
5
>>> push(s1, 7)
>>> top(s1)
7
>>> top(s2)
7
Analytical Breakdown
  1. s1 is initialized as a new stack and populated with 3 and 5.

  2. The statement s2 = s1 performs a reference assignment. It does not clone or deep-copy the stack object; instead, both s1 and s2 point directly to the same underlying tuple and internal list.

  3. Mutating s1 via push(s1, 7) modifies the single underlying list in memory.

  4. Querying top(s2) immediately reflects this change and outputs 7.

Because s2 is an alias rather than an independent copy, in-place modifications made through one reference propagate to all references bound to that object.