Java实现链式栈
public class Stack {
int count;
Node top;
public Stack(){
count=0;
top=null;
}
public void push(Object n) {
Node node=new Node();
node.data=n;
node.next=top;
count++;
top=node;
}
public Object pop() {
if(top!=null) {
Object x=top.data;
top=top.next;
this.count--;
return x;
}else {
return null;
}
}
public int length() {
return this.count;
}
public boolean isEmpty() {
if(top==null)
return true;
else
return false;
}
public Object topvalue() {
if(top!=null)
return top.data;
else
return null;
}
public void print() {
Node p=top;
while(p!=null) {
System.out.print(p.data+" ");
p=p.next;
}
}
class Node{
Object data;
Node next;
Node(){
}
}
public static void main(String[] args) {
Stack stack=new Stack();
stack.push(1);
stack.push('a');
System.out.println("栈中元素数量:"+stack.length());
System.out.print("输出栈:");
}
}