Skip to Content
Course content

398: Implementing a Stack and Queue

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Think about a stack of cafeteria trays. When the dishwasher puts a clean tray down, it goes right on top. When you come along to grab one for your lunch, you take the one from the top. You'd never try to yank the bottom tray out from under the pile unless you wanted a plastic avalanche on your shoes. That's a Stack: Last-In, First-Out (LIFO).

Now, contrast that with a line at a coffee shop. The first person to arrive is the first person who gets their latte. If the barista started serving the person who just walked in the door while everyone else waited, there would be a riot. That's a Queue: First-In, First-Out (FIFO).

The Cafeteria Tray Logic (Stacks)

In Python, you don't actually need a special library to build a stack. A standard list is surprisingly perfect for this. Because we only care about the "top" of the stack, we use append() to push something on and pop() to take it off. Since pop() defaults to the last item in the list, it's an incredibly efficient operation.

# Using a list as a stack
undo_stack = []

# Pushing "actions" onto the stack
undo_stack.append("Typed 'Hello'")
undo_stack.append("Typed ' World'")
undo_stack.append("Changed font to Bold")

print(f"Current state: {undo_stack}")

# The last thing we did is the first thing we undo
last_action = undo_stack.pop() 
print(f"Undoing: {last_action}") # Changed font to Bold
print(f"Remaining stack: {undo_stack}")

I've used an "undo" history here because that's exactly how your favorite text editor works. It doesn't care about the first letter you typed ten minutes ago; it only cares about the very last thing you did.

The Coffee Shop Line (Queues)

Here is where things get tricky. You might be tempted to use a list for a queue, too—using append() to join the line and pop(0) to serve the person at the front. Honestly? Don't do that.

In Python, lists are arrays under the hood. When you pop(0), Python has to shift every single other element in the list one position to the left to fill the gap. If your queue has 10,000 people in it, that's 9,999 movements every time someone is served. It's a performance nightmare.

Instead, we use deque (short for "double-ended queue") from the collections module. It's designed specifically so that adding or removing items from either end happens instantly, regardless of how big the queue is.

from collections import deque

# Creating a queue for a print job
print_queue = deque()

# People sending documents to the printer
print_queue.append("Budget_Report.pdf")
print_queue.append("Vacation_Photos.jpg")
print_queue.append("Resume_Final_v2.docx")

print(f"Queue: {list(print_queue)}")

# Serve the first person in line
current_job = print_queue.popleft() 
print(f"Printing: {current_job}") # Budget_Report.pdf
print(f"Remaining queue: {list(print_queue)}")

Choosing the Right Tool for the Job

The choice usually comes down to how you need to access your data. If you're building a feature like a "Back" button in a browser, you want a Stack—you want to go back to the most recent page. If you're building a system to handle incoming web requests or a task scheduler, you want a Queue—you want to process the oldest request first to ensure fairness.




📋 Practical Task

Implementing a Browser Navigation History Manager

You are building a simplified version of a web browser's navigation system. You need to implement a class called BrowserHistory that manages two different data structures: a stack for the "Back" history and a stack for the "Forward" history.

Your requirements:

  • Implement a visit(url) method: This should push the new URL onto the back_stack and clear the forward_stack (since visiting a new page breaks the forward chain).
  • Implement a go_back() method: This should pop the current page from the back_stack and push it onto the forward_stack, returning the new current page.
  • Implement a go_forward() method: This should pop a page from the forward_stack and push it back onto the back_stack, returning the new current page.
  • Handle "empty" cases: If the user tries to go back or forward but there is no history, return a string saying "No history available".

Example Workflow:

history = BrowserHistory()
history.visit("google.com")
history.visit("github.com")
history.visit("python.org")
print(history.go_back())    # Should return "github.com"
print(history.go_back())    # Should return "google.com"
print(history.go_forward()) # Should return "github.com"
history.visit("stackoverflow.com") 
print(history.go_forward()) # Should return "No history available" (because visit cleared it)
Rating
0 0

There are no comments for now.

to be the first to leave a comment.