数据结构--链栈 java 实现
1.链栈,top指向栈顶元素。顺序栈,和 IStack 接口在这点击打开链接
//节点的定义
class Node{
public Object data;
public Node next;
//无参构造方法
public Node(){
this(null,null);
}
//一个参数的构造方法
public Node(Object data){
this(data,null);
}
//两个参数的构造方法
public Node(Object data, Node next){
this.data = data;
this.next = next;
}
}
//链栈类
public class LinkStack implements IStack{
private Node top; //指向栈顶元素,空栈时为null
//置空栈
@Override
public void clear() {
// TODO Auto-generated method stub
top = null;
}
//判断栈是否为空
@Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return top == null;
}
//查询栈顶元素
@Override
public Object peek() {
// TODO Auto-generated method stub
if(!isEmpty())
return top.data;
return null;
}
//链栈的长度
@Override
public int length() {
// TODO Auto-generated method stub
Node p = top;
int length = 0;
while(p != null){
length++;
p = p.next;
}
return length;
}
//元素入栈
@Override
public void push(Object x) {
// TODO Auto-generated method stub
Node p = new Node(x);
p.next = top;
top = p;
}
//栈顶元素出栈
@Override
public Object pop() {
// TODO Auto-generated method stub
if(isEmpty()){
return null;
}
Node p = top;
top = top.next;
return p.data;
}
/*
* 测试用,忽略
*/
// public static void main(String[] args) throws Exception{
// LinkStack mystack = new LinkStack();
// mystack.push(1);
// mystack.push(2);
// mystack.push(3);
// mystack.push(4);
// mystack.push(5);
// System.out.println(mystack.length());
// System.out.println(mystack.isEmpty());
// System.out.println(mystack.peek());
// for(int i=0;i<5;i++){
// System.out.println(mystack.pop());
// }
// System.out.println(mystack.isEmpty());
// System.out.println(mystack.length());
// }
}