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++
// C++ Program to illustrate how to access the top element // of the stack #include <iostream> #include <stack> using namespace std;
// Driver code int main()
{ // Creating a stack of integers
stack< int > stackData;
// Pushing elements onto the stack
stackData.push(10);
stackData.push(20);
stackData.push(30);
stackData.push(40);
// Accessing the top element of the stack using top()
int res = stackData.top();
// Printing the top element
cout << "Top Element: " << res << endl;
// Printing the stack
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)