![](http://static.javashuo.com/static/loading.gif)
在Java開發中常常會碰到須要你用Java鏈表來實現入棧出棧的模擬操做,下文就這個操做作了一個詳細的描述。
棧:後進先出;最後一個放入堆棧中的物體老是被最早拿出來。
使用鏈表來模擬棧的入棧出棧操做。測試
1.節點類代碼this
public class Entry<T> {
private T value;
private Entry<T> next;
public Entry() {
this(null);
}
public Entry(T value) {
this.value=value;
this.next=null;
}
public void setValue(T value) {
this.value=value;
}
public void setNext(Entry<T> next) {
this.next=next;
}
public T getValue() {
return value;
}
public Entry<T> getNext(){
return next;
}
}
2.節點的入棧出棧方法代碼blog
public class Link<T> {//鏈表實現棧,先進後出
private Entry<T> headEntry;
private int size=0;
public Link() {
headEntry =new Entry<>();
}
public void pop() {//出棧
if(headEntry.getNext()!=null) {
headEntry.getNext().setValue(null);
headEntry.setNext(headEntry.getNext().getNext());
size--;
}else {
return;
}
}
public void push(T value) {//入棧
Entry<T> newEntry=new Entry<>(value);
if(headEntry.getNext()!=null) {
newEntry.setNext(headEntry.getNext());
}
headEntry.setNext(newEntry);
size++;
}
public void show(){//打印節點
if(headEntry.getNext()==null) {
return;
}
for(Entry<T> p = headEntry.getNext();p!=null;p=p.getNext()){
System.out.print(p.getValue()+" ");
}
System.out.println();
}
}
3.測試類代碼開發
public class Main {
public static void main(String args[]) {
Link<String> ll=new Link<>();
ll.push("1");//入棧
ll.push("2");
ll.push("3");
ll.push("4");
ll.push("5");
ll.push("6");
ll.push("7");
ll.push("8");
ll.show();//打印棧內元素
ll.pop();//彈出棧頂元素
ll.show();
ll.pop();
ll.show();
}
}get
4.測試結果class
![](http://static.javashuo.com/static/loading.gif)