package Stack;
class Stacknode{
int data;
Stacknode next;
public Stacknode(int e){
this.data = e;
}
}
public class LinkedStack implements StackIntf{
Stacknode top;
public void push(Object x){
Stacknode s = new Stacknode((Integer) x);
s.next = top;
top = s;
}// 向栈顶添加元素
public Object pop(){
Stacknode p = top;
top = top.next;
return p.data;
}// 删除并返回栈顶元素
public int size(){
int count = 0;
Stacknode p = top;
while(p!=null){
p = p.next;
count++;
}
return count;
}
public void clear(){
top = null;
}
public boolean isEmpty(){
if(top==null){
return true;
}
else
return false;
}//判断栈是否为空
public Object peek(){
return top.data;
}// 取得栈顶元素
public void display(){
Stacknode p = top;
while(p!=null){
System.out.print(p.data+" ");
p = p.next;
}
}//打印栈中元素
public static void main(String[] args) {
LinkedStack ls = new LinkedStack();
ls.push(6);
ls.push(2);
ls.push(4);
ls.push(3);
ls.push(1);
System.out.print("栈从顶至下依次为:");
ls.display();
System.out.println("栈顶出栈元素为:"+ls.pop());
System.out.print("栈从顶至下依次为:");
ls.display();
System.out.println(" ");
System.out.println("栈中共有"+ls.size()+"个元素");
System.out.println("栈顶元素为:"+ls.peek());
System.out.println("栈是否为空:"+ls.isEmpty());
System.out.println("清空栈。。。");
ls.clear();
System.out.println("栈是否为空:"+ls.isEmpty());
}
}
运行结果:
栈从顶至下依次为:1 3 4 2 6 栈顶出栈元素为:1
栈从顶至下依次为:3 4 2 6
栈中共有4个元素
栈顶元素为:3
栈是否为空:false
清空栈。。。
栈是否为空:true