顺序堆栈的表示:
package pk.stack;
public class OrderStack {
private int count;
private int capacity;
private int capacityIncrement;
private Object[] itemArray;
public OrderStack() {// 初始化栈
count = 0;
capacity = 10;
capacityIncrement = 5;
itemArray = new Object[capacity];
}
public boolean isEmpty() {
return (count == 0);
}
public void push(Object x) {
if (count == capacity) {// 栈满时,扩展栈
capacity += capacityIncrement;
Object[] tempArray = new Object[capacity];
for (int i = 0; i < count; i++) {
tempArray[i] = itemArray[i];
}
itemArray = tempArray;
}
itemArray[++count] = x;//将x入栈
}
public Object pop() {//出栈
if(count == 0) {
return null;
} else {
return itemArray[--count];
}
}
public Object peak() {//查看栈顶元素
if(count == 0) {
return null;
} else {
return itemArray[count-1];
}
}
}
链式堆栈表示:
package pk.stack;
public class LinkStack {
Object item;
LinkStack link;
}
class stack {
private LinkStack topNode;
public boolean isEmpty() {
return (topNode == null);
}
public void push(Object x) {// 入栈
LinkStack newNode = new LinkStack();
newNode.item = x;
newNode.link = topNode;
topNode = newNode;
}
public Object pop() {// 出栈
if (topNode == null) {
return null;
} else {
LinkStack tempNode = topNode;
topNode = topNode.link;
return tempNode.item;
}
}
public Object peek() {
if (topNode == null) {
return null;
} else {
return topNode.item;
}
}
}