stack top() in C++ STL
Last Updated :
21 Jun, 2022
Stacks are a type of container adaptors with LIFO(Last In First Out) type of work, where a new element is added at one end called the top of the stack, and an element is removed from the same end only.
stack::top() top() function is used to reference the top(or the newest) element of the stack.
Syntax :
stackname.top()
Parameters: No value is needed to pass as the parameter.
Return Value: Direct reference to the top element of the stack container.
Examples:
Input : stackname.push(5);
stackname.push(1);
stackname.top();
Output : 1
Input : stackname.push(5);
stackname.push(1);
stackname.push(2);
stackname.top();
Output : 2
Errors and Exceptions
- If the stack container is empty, it causes undefined behavior
- It has a no exception throw guarantee if the stack is not empty
C++
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack< int > mystack;
mystack.push(5);
mystack.push(1);
mystack.push(2);
cout << mystack.top();
return 0;
}
|
Output:
2
Time Complexity: O(1)
Auxiliary Space: O(n)
Application :
Given a stack of integers, find the sum of the all the integers.
Input : 1, 8, 3, 6, 2
Output: 20
Algorithm
- Check if the stack is empty, if not add the top element to a variable initialized as 0, and pop the top element.
- Repeat this step until the stack is empty.
- Print the final value of the variable.
C++
#include <iostream>
#include <stack>
using namespace std;
int main()
{
int sum = 0;
stack< int > mystack;
mystack.push(1);
mystack.push(8);
mystack.push(3);
mystack.push(6);
mystack.push(2);
while (!mystack.empty()) {
sum = sum + mystack.top();
mystack.pop();
}
cout << sum;
return 0;
}
|
Output:
20
Time Complexity: O(n)
Auxiliary Space: O(n)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...