0% found this document useful (0 votes)
5 views3 pages

Stack Program1

The document provides implementations of a Stack data structure using both an array and a linked list in Python. It includes methods for common stack operations such as push, pop, peek, checking if the stack is empty, and determining the size of the stack. Example usage and outputs for both implementations are also presented.

Uploaded by

ankush.dhawan178
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views3 pages

Stack Program1

The document provides implementations of a Stack data structure using both an array and a linked list in Python. It includes methods for common stack operations such as push, pop, peek, checking if the stack is empty, and determining the size of the stack. Example usage and outputs for both implementations are also presented.

Uploaded by

ankush.dhawan178
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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

You might also like