Question: Implement peek(stack) that returns, but doesn't remove, the top element from a stack. Return None if list is empty.
I tried many times but did not successfully get it, anyone can help?
My attempt:
def peek_stack(stack):
if stack == []:
return None
else:
s= stack.copy()
return s.pop(0)
peek() – Return the top item in the stack. If the stack is empty, raise an exception. push(value) – Push a value into the head of the stack. pop() – Remove and return a value in the head of the stack.
Peek function in queueA peek function in the python queue is used to print the first element of the queue. It returns the item which is present at the front index of the queue. It will not remove the first element but print it.
Stack. peek() method in Java is used to retrieve or fetch the first element of the Stack or the element present at the top of the Stack. The element retrieved does not get deleted or removed from the Stack. Syntax: STACK.peek()
Python also allows you to index from the end of the list using a negative number, where [-1] returns the last element. This is super-useful since it means you don't have to programmatically find out the length of the iterable in order to work with elements at the end of it.
If you need to use your way to solve this, please use return s.pop()
rather than return s.pop(0)
, because s.pop()
will pop up the last element, but s.pop(0)
will pop up the first element...
And by the way, it's recommend just implement it like this(it can avoid copy your stack, and improve performance)
def peek_stack(stack):
if stack:
return stack[-1] # this will get the last element of stack
else:
return None
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With