Introduction
The peek() operation is used with abstract data types like stacks and queues. This function return the value at the top or front of the collection while keeping the element from the collection in place.
In stack, we have two primary operations push and pop. For these operations, we have a lot of stack operations like isEmpty(), isFull(), etc. But the peek() operation in stack is one of the most important operations which is used to retrieve data.
In this article, we will discuss the peek operation in a stack in detail by implementing in programming languages. We will see how it works generally. Let’s discuss what is peek operation in stack.
What is Peek Operation in Stack?
Peek() is one the most important operations in the stack, which is used to get the top element of the stack without deleting that element. For example, if we have a class of students who are attending exam to get good marks from the teacher and the roll number 1 wants to know what is the last roll number student’s marks. We can apply the peek operation in the stack to get the last student’s marks. Here peek operation is used to get the last student’s marks easily. What if we do not have a peek operation, so this task becomes too difficult? Let’s understand this thing with an example.
Without Peek Operation
If we take the above example, we do not have any peek operation in stack, and we want to find the last student’s marks.
Implementation
Output
The above implementation shows that the for loop is being used to get the last student’s marks. And the time complexity becomes O(n). But what if we use the peek operation in stack.