//用链表实现堆栈
/**
* 节点类
*/
class LinkS {
private long data;
public LinkS next;
public LinkS(long d) {
this.data = d;
}
public String toString() {
return String.valueOf(data);
}
}
/**
* 链表类
*/
class LinkSList {
private LinkS first;
public LinkSList() {
first = null;
}
public void insertFirst(LinkS node) {
node.next = first;
first = node;
}
public LinkS deleteFirst() {
LinkS temp = first;
first = first.next;
return temp;
}
public boolean isEmpty() {
return first == null;
}
public String toString() {
if (isEmpty())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append("[");
LinkS curr = first;
while (curr != null) {
sb.append(curr.toString()).append(",");
curr = curr.next;
}
sb.deleteCharAt(sb.length() - 1);
sb.append("]");
return sb.toString();
}
}
/**
* 栈
*/
class LinkStack {
private LinkSList linkList;
public LinkStack() {
this.linkList = new LinkSList();
}
public void push(LinkS l) {
this.linkList.insertFirst(l);
}
public LinkS pop() {
return this.linkList.deleteFirst();
}
public boolean isEmpty() {
return this.linkList.isEmpty();
}
public String toString() {
return this.linkList.toString();
}
public void display() {
System.out.println(toString());
}
}
public class LinkStackDemo {
public static void main(String[] args) {
LinkStack stack = new LinkStack();
for (int i = 0; i < 5; i++) {
LinkS l = new LinkS(i);
stack.push(l);
stack.display();
}
while (!stack.isEmpty()) {
System.out.print("pop出" + stack.pop());
System.out.print("现在栈为:");
stack.display();
}
}
}