【資料結構】棧與佇列 Part1:棧的建立與相關函式
阿新 • • 發佈:2018-12-01
First.棧(Stack)
定義:後進先出的線性表
操作:
#include<stack> 標頭檔案
stack<int> s; 建立int型別的棧s
s.push(x); 將x放入棧中
s.top(); 讀取棧頂元素
s.pop(); 釋放棧頂
s.size(); 返回棧中元素數目
s.empty(); 若棧為空則返回真,反之則返回假
示範程式碼:
1 #include<iostream> 2 #include<stdio.h> 3 #include<stdlib.h> 4 #include<algorithm> 5 #include<map> 6 #include<stack> 7 #include<queue> 8 9 using namespace std; 10 11 int main()12 { 13 stack<int> s1; 14 int x=3; 15 s1.push(x); 16 cout<<"x="<<s1.top()<<endl; 17 int y; 18 y=s1.top(); 19 cout<<"y="<<y<<endl; 20 cout<<"size: "<<s1.size()<<endl; 21 cout<<"empty? "<<s1.empty()<<endl;22 s1.pop(); 23 cout<<"size: "<<s1.size()<<endl; 24 cout<<"empty? "<<s1.empty()<<endl; 25 return 0; 26 }