Get startedGet started for free

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

This exercise is part of the course

Data Structures and Algorithms in Python

View Course

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

class Stack:
  def __init__(self):
    # Initially there won't be any node at the top of the stack
    ____
    # Initially there will be zero elements in the stack
    self.size = ____
Edit and Run Code