1.Stack的认识
Stack是一种数据类型,叫做栈(先进后出LIFO(Last In First Out)),也是一种容器。
2.Stack的应用
什么是栈呢?如下
如图一,这是一个栈的样子:
(此时字符串里面是12345)
如图2,1进栈(压栈)
(此时字符串里面是2345)
如图3,2、3、4、5进栈(压栈)
(此时字符串里面是NONE)
如图4,5出栈
(此时字符串里面是5)
如图5,全部出栈
(此时字符串里面是54321 = reverse(begin,end))
所以,Stack可以用来做与逆序相同的操作
3.Stack的编写
3.1 STL.stack
库:#include <stack>
声明方式:stack <typename> name;
常用函数:stack.push(int i)进栈
stack.pop()出栈
stack.empty()判断是否为空
stack.top()取出栈顶
3.2 自己编写Stack
首先,我们得学会写类(class),
因为一个Stack它的函数很多,
不可能一个一个的写。
3.2.1 Stack准备
int a[1000]; /*要什么类型写什么类型,int为例*/
int front = 0;
3.2.2 Stack.push()
void push(int n){
if(front == 1000)
return;
a[front++] = n;
}
void push(int nums[],int begin,int end){ /*扩展*/
for(int i = begin;i < end;i++)
a[front++] = nums[i];
if(front == 1000)
return;
}
3.2.3 Stack.pop()
void pop(){
front--;
}
3.2.4 Stack.empty()
bool empty(bool a){
if(a == 0){
if(front == 0)
return 1;
else
return 0;
}else{
if(front > 1000)
return 1;
else
return 0;
}
}
3.2.5 Stack.size()
void size(){
return front;
}
3.2.6 Stack.top() (以下为扩展内容)
int top(){
return a[front - 1];
}
3.2.7 Stack.clear()
void clear(){
front = 0;
}
3.2.8 Stack总体
class Stack{
public:
void clear(){
front = 0;
}
void push(int n){
if(front == 1000)
return;
q[front++] = n;
}
void push(int n[],int begin,int end){
for(int i = begin;i < end;i++){
q[front++] = n[i];
if(front == 1000)
return;
}
}
void pop(){
if(front == 0)
return;
front--;
}
int top(){
return q[front - 1];
}
bool empty(bool a){
if(a == 0){
if(front == 0)
return 1;
else
return 0;
}else{
if(front >= 1000)
return 1;
else
return 0;
}
}
int size(){
return front;
}
private:
int front = 0;
int q[1000];
};