How to Access the Top Element of a Stack in C++?
Last Updated :
04 Mar, 2024
In C++, The stack is a container adapter that provides a Last-In-First-Out (LIFO) type of data structure in which insertion and deletion are done at the end only. In this article, we will learn how to access the top element of a stack in C++.
Example:
Input:
myStack = {10, 20, 30, 40}
Output:
Top Element: 40
Find the Top Element of a Stack in C++
To access the top element of a stack in C++, we can use the std::stack::top() function that retrieves the top element of the stack (if the stack is not empty). This function is mainly used to reference the top element of the stack.
C++ Program to Access the Top Element of a Stack
C++
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack< int > stackData;
stackData.push(10);
stackData.push(20);
stackData.push(30);
stackData.push(40);
int res = stackData.top();
cout << "Top Element: " << res << endl;
cout << "Stack Elements: " ;
while (!stackData.empty()) {
cout << stackData.top() << " " ;
stackData.pop();
}
cout << endl;
return 0;
}
|
Output
Top Element: 40
Stack Elements: 40 30 20 10
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...