cc150第三章栈队列总结

来源:互联网 发布:网络借贷信息披露细则 编辑:程序博客网 时间:2024/05/16 14:53

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());        }    }

0 0
原创粉丝点击