radomaj
0
Q:

implement stack using linked list in python

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class Stack:
    def __init__(self):
        self.head = None

    def isempty(self):
        if self.head == None:
            return True
        else:
            return False

    def push(self, data):
        if self.head == None:
            self.head = Node(data)
        else:
            newnode = Node(data)
            newnode.next = self.head
            self.head = newnode

    def pop(self):
        if self.isempty():
            return None

        else:
            temp = self.head
            self.head = temp.next
            temp.next = None
            return temp.data

    def peek(self):
        if self.isempty():
            return None
        else:
            return self.head.data

    def display(self):
        temp = self.head
        if self.isempty():
            print("Stack underflow")

        else:
            while temp:
                print(temp.data, "->", end = " ")
                temp = temp.next

            return

mystack = Stack()

mystack.push(11)
mystack.push(22)
mystack.push(33)
mystack.push(44)
mystack.push(55)
print()
print(mystack.peek())
mystack.display()
print()
mystack.pop()


mystack.display()
print()
print(mystack.peek())
0

New to Communities?

Join the community