cc150第三章栈队列总结

本文详细介绍了如何使用一个数组实现三个栈,每个栈内部使用Stack类进行管理,当栈达到预设阈值时自动新开一个栈。同时,实现了一个能够返回最小值的栈,并通过实例演示了如何使用两个栈实现队列和如何通过栈对数组进行排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

3.1用一个array实现3个栈

index i+3即可

3.2使栈可以返回min

1.每个node记录min

2.用新栈存储min

3.3 如果一个栈达到设定的threshold就自动新开一个栈

使用ArrayList或stack记录每个栈.

class SetOfStacks<V>{
    Stack<Stack> s = new Stack<Stack>();
    private int num=0;
    SetOfStacks(){
        Stack<V> q = new Stack<V>();
        s.push(q);
    }


    void push(V v){
        Stack p = s.peek();
        p.push(v);
        num++;
        if(num==3){
            Stack<V> q = new Stack<V>();
            s.push(q);
            num=0;
        }
    }
    V pop(){
        if(s.empty()) System.exit(0);
        Stack<V> p = s.peek();
        V res = p.pop();
        if (p.empty()) s.pop();
        return res;
    }
}


4to be continued

5.implement a queue using two stacks

push 的时候把B全部导入A,然后PUSH入A,pop的时候把A全部导入B,从B中pop

6.sort a stack by using another stack

使用tmp来记录pop然后对比答案比自己写的简洁

public static void sortStack(Stack<Integer> s){
        Stack<Integer> t = new Stack<Integer>();
        int tmp = s.pop();
        while (!s.empty()){
            if(tmp<=s.peek()){
                t.push(tmp);
                tmp=s.pop();
            }else{
                int tmp2=s.pop();
                while (!t.empty()){
                    s.push(tmp);
                    tmp=t.pop();
                    if(tmp<=tmp2)break;
                }
                t.push(tmp);
                tmp=tmp2;
            }
        }
        t.push(tmp);
        while (!t.empty()){
            s.push(t.pop());
            System.out.println(s.peek());
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值