Java实现堆栈(list实现)

public interface IStack<T> {
    //元素出栈,并返回出栈元素
    public T pop();
    //元素入栈
    public void push(T element);
    //获取栈顶元素
    public T peek();
    //判断栈是否为空
    public boolean isEmpty();

    public void clear();
}

import java.util.ArrayList;
import java.util.List;

public class ArrayStack<T> implements IStack<T> {
    private List<T> list;
    private int top;
    int size;

    public ArrayStack(){
        list=new ArrayList<T>();
        top=0;
        size=0;
    }
    public T pop() {
        T element = this.list.get(top-1);
        this.list.remove(top-1);
        this.size--;
        return element;
    }

    public void push(T element) {
        list.add(element);
        this.size++;
        this.top++;
    }

    public T peek() {
        return this.list.get(top-1);
    }

    public boolean isEmpty() {
        return this.size==0;
    }

    public int size(){
        return this.list.size();
    }

    public void clear() {

    }

    public static void main(String args[]){
        ArrayStack<Integer> stack = new ArrayStack<Integer>();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        stack.push(5);
        System.out.println(stack.isEmpty());
        System.out.println(stack.peek());
        System.out.println(stack.pop());
        stack.push(5);
        System.out.println(stack.size());
    }
}

 

你可能感兴趣的:(数据结构——堆栈)