链栈的创建,入栈,出栈,取栈顶元素,判空,元素个数

import java.util.*;
class Node{
    int val;
    Node next=null;
    public Node(int val){
        this.val=val;
    }
}

class LinkStack{
    Node top;
    int size;
    public LinkStack(){
        top=null;
        size=0;
    }

    public void Push(int x){
        Node s=new Node(x);
        s.next=top;
        top=s;
        size++;
    }

    public int Pop(){
        if(top==null)
        {
            System.out.println("The stack is empty");
            return -1;
        }
        int x=top.val;
        top=top.next;
        size--;
        return x;
    }

    public int getTop(){
        if(isEmpty()) throw new NullPointerException("The Stack is empty!");
        return top.val;
    }

    public boolean isEmpty()
    {
        if(top==null)
            return true;
        return false;
    }

    public int getSize(){
        return size;
    }

    public void PrintStack(){
        if(top==null)
        {
            System.out.println("The stack is empty!");
            return;
        }
        Node s=top;
        while(s.next!=null)
        {
            System.out.print(s.val+"-->");
            s=s.next;
        }
        System.out.println(s.val);
        return;
    }
}

public class Main{
    public static void main(String args[]){
        LinkStack stack=new LinkStack();
        stack.Push(3);
        stack.Push(4);
        stack.Push(5);
        stack.PrintStack();
        int t=stack.Pop();
        System.out.println("弹出栈顶元素:"+t);
        stack.PrintStack();
        System.out.println("栈的元素个数:"+stack.getSize());
        System.out.println("栈顶元素:"+stack.getTop());
        if(stack.isEmpty())
            System.out.println("The stack is empty!");
        else
            System.out.println("The stack is not empty!");
        stack.PrintStack();
    }
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值