1

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

2
  • 2
    It's because 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. Commented Sep 23, 2021 at 5:43
  • (And change those print statements to return statements, in this case) Commented Sep 23, 2021 at 5:44

1 Answer 1

1

Since you just print the top value, None is always returned by your top function. Change it to return the top value instead of printing it:

    def top(self):
        if self.isEmpty() is  True:
            print("Hey! The stack is Empty")
            return
        else:
            return self.__head.data
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.