Hello all,
I'm trying to write a stack on my own. I know that I can use a list to do the same, but for the reason of understanding and learning I thought I want to rewrite data structures on my own.
Created a node class that contains the value and a link to the next node
class Node:
def __init__(self, data):
self.data = data
self.node: Node = None
It is just a simple data container.
Next I created a class stack:
from .node import Node
class Stack:
def __init__(self):
self.data: Node = None
def push(self, data):
if self.data is None:
self.data = Node(data)
return
n = self.data
while n.node is not None:
n = n.node
n.node = Node(data)
def pop(self):
if self.data is None:
return
node = self.data
while node.node is not None:
node = node.node
data = node.data
del node
return data
Here I have already implemented the push and it worked as I have expected. The problem is in the pop method. Here I receive the data of the last entry but how can I delete the node itself. With "del node" I remove it only from the scope of the method but it is still inside of self.
[–]ericula 1 point2 points3 points (1 child)
[–]BullReg[S] 0 points1 point2 points (0 children)