栈最大的特点就是:先进后出、后进先出,把握这个特点后,我们可以用链表实现栈
/**
* 链接点类
*
* @author zhang
*
*/
public class Link {
public long dData;
public Link next;
public Link(long dData) {
this.dData = dData;
}
public void displayLink() {
System.out.print(dData + " ");
}
}
/**
* 链表类
*
* @author zhang
*
*/
public class LinkList {
private Link first;
public LinkList() {
first = null;
}
public boolean isEmpty() {
return first == null;
}
public void insertFirst(long dd) {
Link newLink = new Link(dd);
newLink.next = first;
first = newLink;
}
public long deleteFirst() {
Link temp = first;
first = first.next;
return temp.dData;
}
public void displayList() {
Link current = first;
while (current != null) {
current.displayLink();
current = current.next;
}
System.out.println();
}
}
/**
* 用链表实现一个栈
* @author zhang
*
*/
public class LinkStack {
private LinkList theList;
public LinkStack(){
theList=new LinkList();
}
public void push(long j){
theList.insertFirst(j);
}
public long pop(){
return theList.deleteFirst();
}
public boolean isEmpty(){
return theList.isEmpty();
}
public void displayStack(){
System.out.print("Stack(top-->bottom):");
theList.displayList();
}
}