用数组+单链表实现栈功能

数组实现

public class ArrayStack {
    public static void main(String[] args) {
        Stack stack = new Stack(100);
        stack.push(3);
        stack.push(4);
        stack.push(5);
       
        stack.pop();
    }
}

class Stack//数组栈实现
{
    public int MAX_NUM;
    int[] arr;//定义一个数组
    int top;

    public Stack(int MAX_NUM)//对数组进行初始化大小
    {
        this.MAX_NUM = MAX_NUM;
        arr = new int[this.MAX_NUM];
        this.top = -1;//初始化数组指针,此时数组为空
    }

    public void push(int num)//添加元素
    {
        if (Full()) {
            System.out.println("数组已满");
            return;

        }
        top++;
        arr[top] = num;

    }

    public boolean empty()//判断数组是否为空
    {
        return this.top == -1 ? true : false;//如果是空,就返回true,否则就返回false


    }

    public boolean Full() //判断栈是否满
    {
        if (this.top == (this.MAX_NUM - 1))
            return true;
        else
            return false;

    }

    public void show_arr()//打印数组
    {
        if (top == -1) {
            System.out.println("队列为空");
            return;
        }
        while (this.top != -1) {
            System.out.println(arr[top]);
            top--;
        }

    }

    public void pop()//弹出栈的第一个数字
    {
        if (Full()) {
            System.out.println("队列为空");
            return;
        }
        System.out.println(arr[top]);
        top--;


    }
}

单链表实现栈功能代码

class Listnode{
    int data;
    Listnode next;

    public Listnode(int data) {
        this.data = data;

    }
}
public class StackList {
    private  Listnode head_node;//定义一个头节点
    int  MAX_NUM;//用来规定栈的容量

    public StackList() {
       head_node =new Listnode(0);
       this.MAX_NUM=5;
    }
    public  void push(int num)
    {
             if(Full())
             {
                 System.out.println("数组满了");
                 return;
             }
         Listnode temp=this.head_node;
        Listnode new_node=new Listnode(num);
        new_node.next=null;
        /**
         * 以下操作就是将结点插入到头节点的下一位中
         */
        new_node.next=head_node.next;
        head_node.next=new_node;
        this.MAX_NUM--;

    }

    public  void pop()
    {
        if(empty())
        {

            System.out.println("栈为空");
            return;
        }
        Listnode temp=this.head_node.next;
        System.out.println(temp.data);
        this.head_node.next=temp.next;
        this.MAX_NUM++;

    }
    public  boolean empty()
    {
        return  this.head_node.next==null? true:false;

    }
    public  boolean Full()
    {
        return  this.MAX_NUM==0? true:false;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值