How to Implement a Stack Data Structure
How to Implement a Stack Data Structure
How to Implement a Stack Data Structure
I need to implement a stack data structure. How can I do this using a list?
solveurit24@gmail.com Changed status to publish February 16, 2025
A stack follows the LIFO (Last In, First Out) principle. You can use a list with specific methods for pushing and popping elements.
Code Example:
class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
def pop(self):
if not self.is_empty():
return self.stack.pop()
return None
def peek(self):
if not self.is_empty():
return self.stack[-1]
return None
def is_empty(self):
return len(self.stack) == 0
def size(self):
return len(self.stack)
# Example usage
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.pop()) # Output: 3
print(stack.peek()) # Output: 2This class provides a basic implementation of a stack with standard operations.
solveurit24@gmail.com Changed status to publish February 16, 2025