一:鏈棧結點
package linkedstack;
/**
* @packagname:linkedstack
* @classname:LinkedStackNode
* @date:2017/1/24
* @author:cullinans
* @des:鏈棧結點
*/
public class LinkedStackNode<T> {
T data;
LinkedStackNode<T> next;
}
二:創建鏈棧結點的工廠類
package linkedstack;
/**
* @packagname:linkedstack
* @classname:LinkedStackNodeFactory
* @date:2017/1/25
* @author:cullinans
* @des:創建鏈式存儲的棧結點的工廠
*/
public class LinkedStackNodeFactory {
public static LinkedStackNode createLinkedStackNode(){
return new LinkedStackNode();
}
}
三:鏈棧的入棧,出棧操作
package linkedstack;
public class LinkedStackList<T> {
int count;
LinkedStackNode<T> top;
public int push(LinkedStackList<T> l,T ele){
LinkedStackNode<T> tempnode=l.top;
LinkedStackNode linkedStackNode = LinkedStackNodeFactory.createLinkedStackNode();
linkedStackNode.data=ele;
linkedStackNode.next=tempnode;
l.top=linkedStackNode;
count++;
return 0;
}
public T pop(LinkedStackList<T> l,T ele){
LinkedStackNode<T> tempNode=l.top;
if(l.top==null){
return null;
}
ele=tempNode.data;
l.top=tempNode.next;
l.count--;
return ele;
}
public static void main(String[] args){
LinkedStackList<Integer> ls=new LinkedStackList<Integer>();
LinkedStackNode<Integer> topnode=LinkedStackNodeFactory.createLinkedStackNode();
topnode.data=1;
ls.top=topnode;
Integer[] elems=new Integer[]{2,3,4,5};
for(int i=0;i<elems.length;i++){
ls.push(ls,elems[i]);
}
ls.printEle(ls);
}
public void printEle(LinkedStackList<T> t){
LinkedStackNode<T> tempnode=t.top;
T tempdata = null;
while(tempnode!=null){
System.out.println(t.pop(t,tempdata));
tempnode=tempnode.next;
}
}
}