0% found this document useful (0 votes)
44 views

Untitled2.ipynb - Colab-Exp2

Uploaded by

Status king
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

Untitled2.ipynb - Colab-Exp2

Uploaded by

Status king
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

10/09/2024, 21:54 Untitled2.

ipynb - Colab

# Stack Implementation using List


class Stack:
def __init__(self):
self.stack = []

# Push element to the stack


def push(self, item):
self.stack.append(item)

# Pop element from the stack


def pop(self):
if not self.is_empty():
return self.stack.pop()
else:
return "Stack is empty"

# Peek at the top element


def peek(self):
if not self.is_empty():
return self.stack[-1]
else:
return "Stack is empty"

# Check if the stack is empty


def is_empty(self):
return len(self.stack) == 0

# Get the size of the stack


def size(self):
return len(self.stack)

# Example usage:
stack = Stack()
stack.push(10)
stack.push(20)
print("Top element:", stack.peek()) # Output: 20
print("Stack size:", stack.size()) # Output: 2
print("Popped element:", stack.pop()) # Output: 20
print("Stack size after pop:", stack.size()) # Output: 1

Top element: 20
Stack size: 2
Popped element: 20
Stack size after pop: 1

# Queue Implementation using List


class Queue:
def __init__(self):
self.queue = []

# Enqueue (add) element to the queue


def enqueue(self, item):
self.queue.append(item)

# Dequeue (remove) element from the queue


def dequeue(self):
if not self.is_empty():
return self.queue.pop(0)
else:
return "Queue is empty"

# Peek at the front element


def peek(self):
if not self.is_empty():
return self.queue[0]
else:
return "Queue is empty"

# Check if the queue is empty


def is_empty(self):
return len(self.queue) == 0

# Get the size of the queue


def size(self):
return len(self.queue)

# Example usage:
queue = Queue()
queue.enqueue(5)
queue.enqueue(15)

https://colab.research.google.com/drive/17tJnxAMAGYk48kObBy1OPXoA1jeR1YZF#scrollTo=n2muSmQ7vzRB&printMode=true 1/2
10/09/2024, 21:54 Untitled2.ipynb - Colab
print("Front element:", queue.peek()) # Output: 5
print("Queue size:", queue.size()) # Output: 2
print("Dequeued element:", queue.dequeue()) # Output: 5
print("Queue size after dequeue:", queue.size()) # Output: 1

Front element: 5
Queue size: 2
Dequeued element: 5
Queue size after dequeue: 1

https://colab.research.google.com/drive/17tJnxAMAGYk48kObBy1OPXoA1jeR1YZF#scrollTo=n2muSmQ7vzRB&printMode=true 2/2

You might also like