Aan de slagGa gratis aan de slag

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

Deze oefening maakt deel uit van de cursus

Data Structures and Algorithms in Python

Cursus bekijken

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

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 = ____
Code bewerken en uitvoeren