《算法筆記》學習筆記
stack 常見用法詳解
stack翻譯為棧,是STL中實現的一個后進先出的容器。‘
1.stack的定義
//要使用stack,應先添加頭文件#include <stack>, 並在頭文件下面加上"using namespace std"
//定義
stack< typename > name;
2. stack容器內元素的訪問
//由於棧(stack)本書就是一種后進先出的數據結構,在STL的stack中只能通過top()來訪問棧頂元素
#include <stdio.h>
#include <stack>
using namespace std;
int main() {
stack<int> st;
for(int i = 1; i <= 5; i++) {
st.push(i); //push(i)用以把i壓入棧,故此處依次入棧 1 2 3 4 5
}
printf("%d\n", st.top()); //top取棧頂元素
return 0;
}
3. stack常用函數實例解析
(1) push()
//push(x)將x入棧,時間復雜度為O(1)
(2) top()
//top()獲得棧頂元素,時間復雜度為O(1)
(3) pop()
//pop()用以彈出棧頂元素,時間復雜度為O(1)
#include <stdio.h>
#include <stack>
using namespace std;
int main() {
stack<int> st;
for(int i = 1; i <= 5; i++) {
st.push(i); //將 1 2 3 4 5 依次入棧
}
for(int i = 1; i <= 3; i++) {
st.pop(); //連續三次將棧頂元素出棧,即將5 4 3 依次出棧
}
printf("%d\n", st.top());
return 0;
}
(4) empty()
//empty()可以檢測stack內是否為空,放回true為空,返回false為非空,時間復雜度為O(1)
#include <stdio.h>
#include <stack>
using namespace std;
int main() {
stack<int> st;
if(st.empty() == true) { //一開始棧內沒有元素,因此棧空
printf("Empty\n");
} else {
printf("Not Empty\n");
}
st.push(1);
if(st.empty() == true) { //入棧"1"后,棧非空
printf("Empty");
} else {
printf("Not Empty\n");
}
return 0;
}
(5) size()
//size()返回stack內元素的個數,時間復雜度為O(1)
#include <stdio.h>
#include <stack>
using namespace std;
int main() {
stack<int> st;
for(int i = 1; i <= 5; i++) {
st.push(i); //push(i)用以將i壓入棧
}
printf("%d\n", st.size()); //棧內有5個元素
return 0;
}
3. stack的常見用途
- 模擬實現一些遞歸,防止程序堆棧內存的現在而導致程序運行出錯