1 栈-OOP

栈实现的是后进先出(先进后出)策略,队列实现的是先进先出策略。

1 栈

栈上的操作主要包括
  1. INSERT操作称为压入(PUSH)。注意上溢问题,即往满栈里添加元素。
  2. 无参数版本的DELETE操作称为弹出(POP)。注意下溢问题,即从空栈上取元素。
  3. STACK-EMPTY判断栈是否为空
栈的实现思路

用一个数组s[1..n]来实现一个最多可容纳n个元素的栈。该数组有一个参数s.top用来指示要插入元素的位置,s[0]是栈底,s[s.top-1]是栈顶。

伪代码

1.判断栈是否为空:

empty()
if stack.top == 0
    return true
else 
    return false

2.插入push

if top > size
    error"upflow"
else
    stack[top] =x;
    top=top+1 

3.删除pop

if empty()
    error "underflow"
else
    pop = pop-1
    return stack[pop]   
栈的模板实现
#include <iostream>

template<class T, const int size = 100>
class Stack{
    T s[size];
    int top;
public:
    Stack():top(0){}
    bool empty(){ return top == 0;}
    T pop(){
        if(top <= 0){
            std::cerr << "下溢";
            exit(0);
        }
        return s[--top];
    }
    void push(T t){
        if(top >= size){
            std::cerr << "上溢";
            exit(0);
        }
        s[top++] = t;
    }
};
//测试代码
int main(){
    const int size = 10;
    Stack<int, size> si;
    for (int i = 0; i < size; i++){
        std::cout << i;
        si.push(i);
    }
    std::cout << std::endl;
    while(!si.empty())
        std::cout << si.pop();
}
在一个数组中实现两个栈,使当两个栈元素个数之和不为n时,都不会上溢。PUSH和POP操作的运行时间都为O(1)

要2个栈公用一个存储空间,栈顶指针从两端指针开始,当两端指针指向同一个内存时则发生上溢。

#include <iostream>

template<class T, const int size = 100>
class Stack{
    T s[size];
    int top1;
    int top2;
public:
    Stack():top1(0),top2(size-1){}
    bool empty(int index){ 
        if(index == 1)
            return top1 == 0;
        else
            return top2 == size-1;
    }
    T pop(int index){
        if(index ==1 && top1 == 0){
            std::cerr << "下溢";
            exit(0);
        }
        if(index == 2 && top2 == size-1){
            std::cerr << "下溢";
            exit(0);
        }
        if(index ==1 )
            return s[--top1];
        else
            return s[++top2];
    }
    void push(T t, int index){
        if(top1 == top2){
            std::cerr << "上溢";
            exit(0);
        }
        if(index == 1)
            s[top1++] = t;
        else
            s[top2--] = t;
    }
};

int main(){
    const int size = 10;
    Stack<int, size> si;
    for (int i = 0; i < 4; i++){
        std::cout << i;
        si.push(i,1);
    }
    std::cout << std::endl;
    for (int i = 0; i < 5; i++){
        std::cout << i;
        si.push(i,2);
    }
    std::cout << std::endl;
    while(!si.empty(1))
        std::cout << si.pop(1);
    std::cout << std::endl;
    while(!si.empty(2))
        std::cout << si.pop(2);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值