I am trying to implement Stack Using Linked List but whenever I try to use any functionality it returns an extra None with it. I don't know why it's happening. My desired output should not contain the keyword None after every Operation. Can Somebody let me know what's wrong here?
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.__head = None
self.__count = 0
def push(self, ele):
newNode = Node(ele)
newNode.next = self.__head
self.__head = newNode
self.__count = self.__count + 1
def pop(self):
if self.isEmpty() is True:
print("Hey! The stack is Empty")
return
else:
pop = self.__head.data
self.__head = self.__head.next
self.__count = self.__count - 1
return pop
def top(self):
if self.isEmpty() is True:
print("Hey! The stack is Empty")
return
else:
pop = self.__head.data
print(pop)
def size(self):
return self.__count
def isEmpty(self):
return self.__count == 0
s = Stack()
s.push(15)
print(s.top())
s.push(16)
print(s.pop())
print(s.top())
Output
15
None
16
None
16
15
None
s.top()does not return anything. You're printing what it returns, which is None. In general, it's better to have the function just return a value, and let the caller decide what to do with it, like print it. That is, remove the print statements from your functions.