Implement a stack data structure with push, pop, and peek operations.
- User
Implement a stack data structure with push, pop, and peek operations.
Assistant
Implement a stack data structure with push, pop, and peek operations.
The user wants an implementation of a stack data structure. The implementation needs to support three core operations:
push: Add an element to the top.pop: Remove and return the element from the top.peek: Return the element at the top without removing it.I should choose a programming language. Python is a good default for readability, but providing a few options (like Python, Java, and C++) is often better to be helpful to a wider audience. I'll focus on Python first as the primary example, then perhaps add others or just stick to Python if the request implies a single solution. The request is generic ("Implement a stack..."), so a Python class-based implementation is standard.
Key Considerations for a Stack:
Drafting the Python Implementation (using a list):
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
raise IndexError("pop from empty stack")
def peek(self):
if not self.is_empty():
return self.items[-1]
raise IndexError("peek from empty stack")
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
Drafting the Java Implementation:
(using ArrayList or LinkedList. Standard library Stack extends Vector, but often interview questions ask to implement it from scratch).
import java.util.ArrayList;
import java.util.List;
import java.util.EmptyStackException;
public class MyStack {
private List<Integer> stack;
public MyStack() {
this.stack = new ArrayList<>();
}
public void push(int item) {
stack.add(item);
}
public int pop() {
if (stack.isEmpty()) {
throw new EmptyStackException();
}
return stack.remove(stack.size() - 1);
}
public int peek() {
if (stack.isEmpty()) {
throw new EmptyStackException();
}
return stack.get(stack.size() - 1);
}
}
Drafting the C++ Implementation:
(using std::vector or std::list).
#include <vector>
#include <stdexcept>
class Stack {
private:
std::vector<int> items;
public:
void push(int item) {
items.push_back(item);
}
int pop() {
if (items.empty()) {
throw std::out_of_range("Stack is empty");
}
int top = items.back();
items.pop_back();
return top;
}
int peek() {
if (items.empty()) {
throw std::out_of_range("Stack is empty");
}
return items.back();
}
};
Refining the output: I will provide the Python implementation as the primary answer because it's concise and easy to read. I will also include a Java and C++ version for completeness. I should explain the logic (LIFO) and the time complexity.
Structure of the answer:
Let's stick to Python for the main code block to keep it clean, but offer the others. Actually, just Python is usually sufficient unless specified. I'll provide the Python one with comments explaining the time complexity.
Self-Correction: The prompt just says "Implement a stack". It doesn't specify the language. Python is the safest bet for pseudo-code-like clarity. I will add a Node-based implementation as well? No, that's usually overkill unless "using Linked List" is specified. Array-based is standard.
Let's write out the Python code clearly. I'll include is_empty and size as helper methods because they are standard boilerplate for stack classes, even though only push, pop, and peek were strictly asked for.
Plan:
Stack.__init__: Initialize list.push: Use list.append.pop: Check empty -> list.pop.peek: Check empty -> list[-1].I will also briefly mention the Time Complexity: O(1) for all operations (amortized).
Let's verify the specific requirements: "push, pop, and peek". Okay, I'll stick to those core methods plus the constructor.
Python Code:
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 self.is_empty():
raise IndexError("Pop from empty stack")
return self.items.pop()
def peek(self):
if self.is_empty():
raise IndexError("Peek from empty stack")
return self.items[-1]
This looks solid. I will present this clearly.
I'll also add a Java example since it's a very common interview language. I'll put it in a collapsible section or just below. Actually, distinct sections are better.
Final Output Structure:
Wait, is there any nuance? "Implement a stack". It could mean using two queues (common interview trick), but usually, it means a standard stack. I'll assume the standard definition using a dynamic array.
Let's check constraints. None provided. Generic implementation is best.
One detail: Should I handle thread safety? No, standard implementations are not thread-safe unless specified. Should I limit capacity? No, dynamic sizing is standard.
I will proceed with the standard Python list-based approach. It is the most pragmatic.
Step 1: Python Implementation. Step 2: Example usage. Step 3: Brief complexity analysis.
The user didn't specify a language, so I will provide Python (easiest to read), and perhaps Java or C++ as alternatives. I'll focus on Python first.
The code:
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if not self.items:
return None # Or raise error? Raising error is more Pythonic for stacks.
return self.items.pop()
def peek(self):
if not self.items:
return None
return self.items[-1]
Raising IndexError is strictly correct for Python lists, but returning None is often friendlier for simple implementations. I'll stick to raising exceptions as it mimics the standard library behavior more closely.
Let's refine the Java version.
Using ArrayList is O(1) amortized. Using LinkedList is O(1) guaranteed. ArrayList is usually preferred due to locality of reference unless insertions are happening in the middle (which they aren't for stacks).
I will provide the Python solution as the primary answer. Here is an implementation of a Stack data structure in Python using a list.
A Stack follows the LIFO (Last-In, First-Out) principle, meaning the last element added is the first one to be removed.
class Stack:
def __init__(self):
"""Initialize an empty stack."""
self.items = []
def push(self, item):
"""Add an item to the top of the stack."""
self.items.append(item)
def pop(self):
"""
Remove and return the item from the top of the stack.
Raises an error if the stack is empty.
"""
if self.is_empty():
raise IndexError("Pop from empty stack")
return self.items.pop()
def peek(self):
"""
Return the item at the top of the stack without removing it.
Raises an error if the stack is empty.
"""
if self.is_empty():
raise IndexError("Peek from empty stack")
return self.items[-1]
def is_empty(self):
"""Check if the stack is empty."""
return len(self.items) == 0
def size(self):
"""Return the number of items in the stack."""
return len(self.items)
# --- Example Usage ---
if __name__ == "__main__":
my_stack = Stack()
# Push items
my_stack.push(10)
my_stack.push(20)
my_stack.push(30)
print(f"Stack size: {my_stack.size()}") # Output: 3
print(f"Top item: {my_stack.peek()}") # Output: 30
# Pop item
popped_item = my_stack.pop()
print(f"Popped item: {popped_item}") # Output: 30
print(f"New top item: {my_stack.peek()}") # Output: 20
Using a Python list as the underlying data structure provides the following time complexities: