1. Learn
  2. /
  3. Courses
  4. /
  5. Data Structures and Algorithms in Python

Connected

Exercise

Implementing a Stack with the push method

In the last video, you learned how to implement stacks in Python. As you saw, stacks follow the LIFO principle; the last element inserted is the first element to come out.

In this exercise, you will follow two steps to implement a stack with the push() operation using a singly linked list. You will also define a new attribute called size to track the number of items in the stack. You will start coding the class to build a Stack(), and after that, you will implement the push() operation.

To program this, you will use the Node() class that has the following code:

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

Instructions 1/2

undefined XP
    1
    2
  • Assign no value to the top node and set self.size with zero elements.