STACK Implementation Using Array
class Stack:
def __init__(self):
[Link] = []
def push(self, element):
[Link](element)
def pop(self):
if [Link]():
return "Stack is empty"
return [Link]()
def peek(self):
if [Link]():
return "Stack is empty"
return [Link][-1]
def isEmpty(self):
return len([Link]) == 0
def size(self):
return len([Link])
# Create a stack
myStack = Stack()
[Link]('A')
[Link]('B')
[Link]('C')
print("Stack: ", [Link])
print("Pop: ", [Link]())
print("Stack after Pop: ", [Link])
print("Peek: ", [Link]())
print("isEmpty: ", [Link]())
print("Size: ", [Link]())
Out put:
Stack: ['A', 'B', 'C']
Pop: C
Stack after Pop: ['A', 'B']
Peek: B
isEmpty: False
Size: 2
STACK Implementation Using Linked List
class Node:
def __init__(self, value):
[Link] = value
[Link] = None
class Stack:
def __init__(self):
[Link] = None
[Link] = 0
def push(self, value):
new_node = Node(value)
if [Link]:
new_node.next = [Link]
[Link] = new_node
[Link] += 1
def pop(self):
if [Link]():
return "Stack is empty"
popped_node = [Link]
[Link] = [Link]
[Link] -= 1
return popped_node.value
def peek(self):
if [Link]():
return "Stack is empty"
return [Link]
def isEmpty(self):
return [Link] == 0
def stackSize(self):
return [Link]
def traverseAndPrint(self):
currentNode = [Link]
while currentNode:
print([Link], end=" -> ")
currentNode = [Link]
print()
myStack = Stack()
[Link]('A')
[Link]('B')
[Link]('C')
print("LinkedList: ", end="")
[Link]()
print("Peek: ", [Link]())
print("Pop: ", [Link]())
print("LinkedList after Pop: ", end="")
[Link]()
print("isEmpty: ", [Link]())
print("Size: ", [Link]())
OUT PUT: LinkedList: C -> B -> A ->
Peek: C
Pop: C
LinkedList after Pop: B -> A ->
isEmpty: False
Size: 2