标签:val idp zcl private 使用 count c89 分享 eem
用链表实现栈:
链表栈:
package com.lt.datastructure.stackqueue; /* * 使用链表实现栈 */ public class LinkedListStack<E> implements Stack<E> { LinkedList<E> list; 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("pop: \n"+stack); } }
测试:
和数组栈比较:
测试用例:
package com.lt.datastructure.stackqueue; import java.util.Random; public class Main { // 测试使用stack运行opCount个push和pop操作所需要的时间,单位:秒 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 = 100000; 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"); // 其实这个时间比较很复杂,因为LinkedListStack中包含更多的new操作 } }
测试结果:链表栈比数组栈快一些,但没有复杂度上的巨大差异
标签:val idp zcl private 使用 count c89 分享 eem
原文地址:https://www.cnblogs.com/ltfxy/p/9986512.html