Skip to Content
Python Data Structures and Algorithms
book

Python Data Structures and Algorithms

by Benjamin Baka
May 2017
Intermediate to advanced
310 pages
8h 5m
English
Packt Publishing
Content preview from Python Data Structures and Algorithms

Stack implementation

Now let us study an implementation of a stack in Python. We start off by creating a node class, just as we did in the previous chapter with lists:

class Node:     def __init__(self, data=None):         self.data = data         self.next = None 

This should be familiar to you by now: a node holds data and a reference to the next item in a list. We are going to implement a stack instead of a list, but the same principle of nodes linked together still applies.

Now let us look at the stack class. It starts off similar to a singly linked list. We need to know the node at the top of the stack. We would also like to keep track of the number of nodes in the stack. So we will add these fields to our class:

class Stack:     def __init__(self):  self.top ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Data Structures and Algorithms in Python

Data Structures and Algorithms in Python

Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser
Hands-On Data Structures and Algorithms with Python - Second Edition

Hands-On Data Structures and Algorithms with Python - Second Edition

Dr. Basant Agarwal, Benjamin Baka, David Julian
Data Structures & Algorithms in Python

Data Structures & Algorithms in Python

John Canning, Alan Broder, Robert Lafore

Publisher Resources

ISBN: 9781786467355Supplemental Content