【数据结构】JAVA实现链栈的相关操作

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值