从上一篇博客链表( 自定义链表)知道,链表如果增删只对链表头操作O(1), 查找链表头元素O(1) ,这样的操作符合栈这个数据结构。
下面我们使用自定义链表实现自定义栈
1、前面定义的栈接口
public interface IStack<E> {
int getSize();
boolean isEmpty();
void push(E e);
E pop();
E peek();
}
2、自定义栈。
LinkedList类来自链表( 自定义链表)
public class LinkedListStack<E> implements IStack<E> {
private LinkedList<E> list;
public LinkedListStack(){
list = new LinkedList<E>();
}
public int getSize() {
return list.getSize();
}
public boolean isEmpty() {
return list.isEmpty();
}
public void push(E e) {
list.addFirst(e);
}
public E pop() {
return list.removeFirst();
}
public E peek() {
return list.getFirst();
}
@Override
public String toString() {
StringBuilder res = new StringBuilder();
res.append("栈Stack: (左侧栈顶) ");
res.append(list);
return res.toString();
}
public static void main(String[] args) {
LinkedListStack<Integer> stack = new LinkedListStack<Integer>();
for(int i = 0; i < 5; i++){
stack.push(i);
System.out.println(stack);
}
System.out.println("出栈 pop stack...");
stack.pop();
System.out.println(stack); //输出: Stack: [0, 1, 2, 3]
}
}
测试:
public static void main(String[] args) {
LinkedListStack<Integer> stack = new LinkedListStack<Integer>();
for(int i = 0; i < 5; i++){
stack.push(i);
System.out.println(stack);
}
System.out.println("出栈 pop stack...");
stack.pop();
System.out.println(stack); //输出: Stack: [0, 1, 2, 3]
}
测试结果如下:
栈Stack: (左侧栈顶) 链表头 0->NULL 栈Stack: (左侧栈顶) 链表头 1->0->NULL 栈Stack: (左侧栈顶) 链表头 2->1->0->NULL 栈Stack: (左侧栈顶) 链表头 3->2->1->0->NULL 栈Stack: (左侧栈顶) 链表头 4->3->2->1->0->NULL 出栈 pop stack... 栈Stack: (左侧栈顶) 链表头 3->2->1->0->NULL
3、数组实现的栈和链表实现的栈进行比较
public class TowStackCompareTest {
//测试使用stack运行opCount个push和pop操作所需要的时间,单位: 秒
private static double testStack(IStack<Integer> q, int opCount) {
long startTime = System.nanoTime();
Random random = new Random();
for (int i = 0; i < opCount; i++) {
q.push(random.nextInt(Integer.MAX_VALUE));
}
for (int i = 0; i < opCount; i++) {
q.pop();
}
long endTime = System.nanoTime();
return (endTime - startTime) / 1000000000.0;
}
public static void main(String[] args) {
int opCount = 1000000;
ArrayStack<Integer> arrayQueue = new ArrayStack<Integer>();
double time1 = testStack(arrayQueue, opCount);
System.out.println("ArrayStack, time: " + time1 + "秒");
LinkedListStack<Integer> linkedListStack = new LinkedListStack<Integer>();
double time2 = testStack(linkedListStack, opCount);
System.out.println("LinkedListStack, time: " + time2 + "秒");
}
}
输出结果如下:
ArrayStack, time: 0.065099119秒 LinkedListStack, time: 0.246462526秒
将opCount 改成10000000;
int opCount = 10000000;
输出结果如下:
ArrayStack, time: 2.446045165秒 LinkedListStack, time: 5.529615999秒
这是因为使用链表,需要创建Node(New空间),这个动作比较耗时。