栈--链表实现:
package org.zp.datastruct;
public class LinkedStack implements Stack {
// 链表节点类
private static class SLLNode {
private Object data;
private SLLNode next;
public SLLNode() {
}
public SLLNode(Object data) {
this.data = data;
}
public SLLNode(Object data, SLLNode next) {
this.data = data;
this.next = next;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public SLLNode getNext() {
return next;
}
public void setNext(SLLNode next) {
this.next = next;
}
public String toString() {
return data.toString();
}
}
private SLLNode top;
private int count;
public LinkedStack() { // 初始化 空栈,栈深度任意
clear();
}
@Override
public void clear() {
top = null;
count = 0;
}
@Override
public boolean isEmpty() {
return top == null;
}
@Override
public Object peek() {
if (top == null) {
throw new IllegalStateException();
}
return top.data;
}
@Override
public Object pop() {
if (top == null) {
throw new IllegalStateException();
}
Object val = top.data;
top = top.next;
count--;
return val;
}
@Override
public void push(Object obj) {
top = new SLLNode(obj, top);
count++;
}
@Override
public int size() {
return count;
}
public String toString() {
String buf = "[ ";
for (SLLNode curr = top; curr != null; curr = curr.next) {
if (curr != top) {
buf += ", ";
}
buf += curr.data;
}
buf += " ]";
return buf;
}
}