package MyJava2;
public class LinkStack {
private class Node{
String data;
Node next;
public Node(){}
public Node(String data,Node next){
this.data=data;
this.next=next;
}
}
private Node top;
private int size=0;
public LinkStack(){//建立空栈
top=null;
size=0;
}
public LinkStack(String data){//指定元素建栈
top=new Node(data,null);
size++;
}
public int len(){
return size;
}
public void push(String data){//进栈
top=new Node(data,top);
size++;
}
public String pop(){//出栈
Node old=top;
top=top.next;
old.next=null;
size--;
return old.data;
}
public String peek(){//访问栈顶元素但不删除
return top.data;
}
public boolean empty(){//判断是否是空栈
return size==0;
}
public void clear(){//清空链栈
top=null;
size=0;
}
public String toString(){
StringBuffer sb=new StringBuffer();
Node current=top;
for(;current!=null;current=current.next){
sb.append(current.data+",");
}
return sb.toString();
}
public static void main(String[] args){
LinkStack stack=new LinkStack("A");
stack.push("B");
stack.push("C");
System.out.println(stack.toString());
System.out.println(stack.pop());
System.out.println(stack.peek());
System.out.println(stack.size);
stack.clear();
System.out.println(stack.empty());
}
}
栈的链式存储结构
最新推荐文章于 2022-09-13 13:26:49 发布