链表栈的实现以及与数组栈的对比

引入上篇中实现的链表类,同时定义一个Stack的接口

public class LinkedListStack<E> implements Stack<E> {

    private LinkedList<E> list;

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

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

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

    @Override
    public void push(E e) {
        list.addFirst(e);
    }

    @Override
    public E pop() {
        return list.removeFirst();
    }

    @Override
    public E peek() {
        return list.getFirst();
    }

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        res.append("Stack: top ");
        res.append(list);
        return res.toString();
    }
}

测试实现的链表栈

    public static void main(String[] args) {
        LinkedListStack<Integer> stack = new LinkedListStack<>();
        for (int i = 0; i < 5; i++) {
            stack.push(i);
            System.out.println(stack);
        }
        stack.pop();
        System.out.println(stack);
    }

与数组栈进行对比:

public class Main{

    //测试使用stack运行opCount个push和pop操作所需要的时间,单位:s
    private static double testStack(Stack<Integer> stack,int opCount){
        long startTime=System.nanoTime();

        Random random = new Random();
        for(int i = 0;i<opCount;i++)
            stack.push(random.nextInt(Integer.MAX_VALUE));
        for(int i=0;i<opCount;i++)
            stack.pop();

        long endTime=System.nanoTime();

        return (endTime-startTime)/1000000000.0;
    }
    public static void main(String[] args) {
        int opCount=10000000;
        ArrayStack<Integer> stack=new ArrayStack<>();

//        for(int i=0;i<5;i++){
//            stack.push(i);
//            System.out.println(stack);
//        }
//        stack.pop();
//        System.out.println(stack);

        ArrayStack<Integer> arrayStack=new ArrayStack<>();
        double time1=testStack(arrayStack,opCount);
        System.out.println("ArrayStack,time:"+time1+"s");

        LinkedListStack<Integer> linkedListStack=new LinkedListStack<>();
        double time2=testStack(linkedListStack,opCount);
        System.out.println("LinkedListStack,time:"+time2+"s");
    }
}

猜你喜欢

转载自blog.csdn.net/qq_25366173/article/details/80299435
今日推荐