java数据结构——链表实现栈
package fwb.COllection;
class LLNode{
private Object data;
private LLNode next;
public LLNode(){}
public LLNode(Object data){
this.data =data;
}
public Object getData(){
return data;
}
public void setData(Object data){
this.data = data;
}
public LLNode getNext(){
return next;
}
public void setNext(LLNode next){
this.next = next;
}
}
public class StackLL {
LLNode headNode = null;
public StackLL(){
headNode = new LLNode(null);
}
public void push(Object data){
if(headNode.getData() == null){
headNode.setData(data);
}
else if(headNode == null){
headNode = new LLNode(data);
}
else{
LLNode newNode = new LLNode(data);
newNode.setNext(headNode);
headNode = newNode;
}
}
public boolean isEmpty(){
return headNode == null;
}
public Object pop(){
Object data = null;
if(isEmpty()){
System.out.println("栈为空");
return 0;
}
data = headNode.getData();
headNode = headNode.getNext();
return data;
}
public int getLength(){
int count = 0;
LLNode cur = headNode;
if(isEmpty()||cur.getData()==null){
count = 0;
}
else{
while(cur != null){
count++;
cur = cur.getNext();
}
}
return count;
}
public static void main(String[] args) {
StackLL stackll = new StackLL();
stackll.push(1);
stackll.push(2);
stackll.push(3);
System.out.println("个数为:"+stackll.getLength());
Object obj = stackll.pop();
System.out.println("弹出了元素:"+obj);
System.out.println("弹出后个数为:"+stackll.getLength());
}
}
|