基于数组实现

public class ArrayStack{
    Array array;

    public ArrayStack(int capacity){
        array = new Array(capacity);
    }

    public ArrayStack(){
        array = new Array();
    }

    public int getSize(){
        return array.getSize();
    }

    public boolean isEmpty(){
        return array.isEmpty();
    }

    public int getCapacity(){
        return array.getCapacity();
    }

    pulic void push(int e){
        array.addLast(e);
    }

    public int pop(){
        return array.removeLast();
    }

    public int peek(){
       return array.getLast();
    }
}

基于链表实现

public class LinkedListStack{
    private LinkedList list;

    public LinkedListStack(){
        list = new LinkedList();
    }

    public int getSize(){
        return list.getSize();
    }

    public boolean isEmpty(){
        return list.isEmpty();
    }

    public void push(Integer e){
        list.addFirst(e);
    }

    public Integer pop(){
        return list.removeFirst();
    }

    public Integer peek(){
        return list.getFirst();
    }
}

栈的应用

    public boolean isValid(String s){
        Stack<Character> stack = new Stack();
        for(int i = 0; i < s.length(); i++){
            char c = s.charAt(i);
            if(c == '(' || c == '[' || c == '{'){
                stack.push(c);
            }else{
                if(stack.isEmpty()){
                    return false;
                }
                char topChar = stack.pop();
                if(c == ')' && topChar != '('){
                    return false;
                }
                if(c == ']' && topChar != '['){
                    return false;
                }
                if(c == '}' && topChar != '{'){
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }

发表评论

发表
Table of Contents