public LinkedListStack(){
linkedList = new LinkedList<>();
}
// 把链表头作为栈顶,始终对链表头进行操作
// 入栈
@Override
public void push(E element) {
linkedList.addFirst(element);
}
// 出栈
@Override
public E pop() {
return linkedList.removeFirst();
}
// 查看栈顶元素
@Override
public E peek() {
return linkedList.getFirst();
}
// 查看栈中元素个数
@Override
public int getSize() {
return linkedList.getSize();
}
// 查看栈是否为空
@Override
public boolean isEmpty() {
return linkedList.isEmpty();
}
@Override
public String toString() {
return “Stack: top [” + linkedList + “] tail”;
}
// main函数测试
public static void main(String[] args) {
LinkedListStack stack = new LinkedListStack<>();
for (int i=0;i<5;i++){
stack.push(i);
System.out.println(stack);
}
stack.pop();
System.out.println(stack);
}
}
/*
输出结果:
Stack: top [0->null] tail
Stack: top [1->0->null] tail
Stack: top [2->1->0->null] tail
Stack: top [3->2->1->0->null] tail
Stack: top [4->3->2->1->0->null] tail
Stack: top [3->2->1->0->null] tail
*/
##数组栈VS链表栈
截至目前,我们已经通过两种方式实现了栈,接下来不妨对比一下两种实现方式的性能孰高孰低。可以通过出栈和入栈两种操作进行评估:
package com.algorithm.stack;
import java.util.Random;
public class PerformanceTest {
public static double testStack(Stack stack, int testNum){
// 起始时间
long startTime = System.nanoTime();
// 使用随机数测试
Random random = new Random();
// 入栈测试
for (int i=0;i<testNum;i++) stack.push(random.nextInt(Integer.MAX_VALUE));
// 出栈测试
for (int i=0;i<testNum;i++) stack.pop();
// 结束时间
long endTime = System.nanoTime();
// 返回测试时长
return (endTime - startTime) / 1000000000.0;
}
public static void main(String[] args) {
// 数组栈
ArrayStack arrayStack = new ArrayStack<>();
double arrayTime = testStack(arrayStack, 1000000);
System.out.println(&