Stacks and queues are fundamental data structures used in computer science to manage and organize data. Let's get started with stacks and queues in Python.
Stacks:
A stack is a Last In, First Out (LIFO) data structure, where the last element added is the first one to be removed. Think of it like a stack of plates - you can only take the top plate off.
Implementation in Python:
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
else:
raise IndexError("pop from an empty stack")
def peek(self):
if not self.is_empty():
return self.items[-1]
else:
raise IndexError("peek from an empty stack")
def size(self):
return len(self.items)
Example usage:
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print("Stack:", stack.items)
print("Pop:", stack.pop())
print("Stack after pop:", stack.items)
print("Peek:", stack.peek())
print("Stack size:", stack.size())
Queues:
A queue is a First In, First Out (FIFO) data structure, where the first element added is the first one to be removed. Think of it like a queue of people waiting in line.
Implementation in Python:
class Queue:
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def enqueue(self, item):
self.items.append(item)
def dequeue(self):
if not self.is_empty():
return self.items.pop(0)
else:
raise IndexError("dequeue from an empty queue")
def front(self):
if not self.is_empty():
return self.items[0]
else:
raise IndexError("front from an empty queue")
def size(self):
return len(self.items)
Example usage:
queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
print("Queue:", queue.items)
print("Dequeue:", queue.dequeue())
print("Queue after dequeue:", queue.items)
print("Front:", queue.front())
print("Queue size:", queue.size())
These basic implementations should get you started with stacks and queues in Python. Feel free to modify and expand upon them based on your specific needs.
0 Comments:
Post a Comment