Yes, an alternate way to implement the
peek method depends on the data structure you’re working with.
If you’re using a stack, you can implement the
peek method by returning the top element of the stack without removing it. For example, in Python:
def peek(stack): if not stack: return None # Stack is empty return stack[-1] # Return the top element of the stack
If you’re using a queue, you can implement the
peek method by returning the front element of the queue without dequeuing it. Here’s an example using Python’s
deque from the
from collections import deque def peek(queue): if not queue: return None # Queue is empty return queue # Return the front element of the queue
These are just a couple of examples, and the implementation may vary depending on the specific data structure or programming language you’re using.