Common usage of the stack
stack translated into a stack, STL is implemented in a LIFO container
head File
#include<stack>
using namespace std;
Defined stack of
stack<typename> name;
Access within the stack container element
Only through top()
access to the top element
#include<iostream>
#include<stack>
using namespace std;
int main(){
stack<int> st;
for(int i = 1; i <= 5; i++)
st.push(i);
printf("%d", st.top()); // 5
return 0;
}
stack of commonly used functions
push( )
Push (x) of x onto the stack, the time complexity is O (1)
top( )
top () to access the top element, the time complexity is O (1)
pop( )
pop () to pop the top element, the time complexity is O (1)
#include<iostream>
#include<stack>
using namespace std;
int main(){
stack<int> st;
for(int i = 1; i <= 5; i++)
st.push(i);
for(int i = 1; i <= 3; i++)
st.pop(); // 出栈3次
printf("%d", st.top()); // 2
return 0;
}
empty( )
empty () may detect the Stack is empty, return true empty, not empty returns false, the time complexity is O (1)
size( )
size () returns the number of elements in the stack, the time complexity is O (1)
#include<iostream>
#include<stack>
using namespace std;
int main(){
stack<int> st;
for(int i = 1; i <= 5; i++)
st.push(i);
for(int i = 1; i <= 3; i++)
st.pop(); // 出栈3次
st.empty() ? printf("Empty\n") : printf("No Empty\n");
printf("%d\n", st.size());
printf("%d", st.top());
return 0;
}
No Empty
2
2
Common uses of the stack
- Used to simulate implement some recursive prevent restrictions on the procedures which led to the stack memory to run error
Write by Gqq