1. 程式人生 > >連結串列棧的實現以及與陣列棧的對比

連結串列棧的實現以及與陣列棧的對比

引入上篇中實現的連結串列類,同時定義一個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");
}
}