自己实现一个栈

1.使用LinkedList来实现

其实是利用其addLast方法
对于list, 依次加入1, 2, 3,list.add()实际是list.addLast();

class MyStack{
    private LinkedList<Integer> list = new LinkedList<>();
    public MyStack(){

    }
    public boolean isEmpty(){//判断是否为空
        return list.isEmpty();
    }
    public int pop(){
        if(!isEmpty()) return list.removeFirst();
        else throw new EmptyStackException();
    }
    public void push(int val){
        list.addFirst(val);
    }
    public void clear(){
        list.clear();
    }
}

本质是一个双向链表,用链表来实现

新建一个链表,Node类
新建一个stack

class Node{
    Object data;
    Node next;

    public Node(Object val){
        this.data = val;
        this.next = null;
    }

}
class MyStack{
    Node head;//假的头结点
    public MyStack(){
        head = new Node(-1);
    }
    public boolean isEmpty(){
        return head.next == null;
    }
    public void push(Object data){
        Node node = new Node(data);
        node.next = head.next;
        head.next = node;
    }
    public Object pop(){
        if(isEmpty()){
            System.out.println("当前栈为空");
            return -1;
        }
        Node next = head.next;
        head.next = next.next;
        return next.data;
    }
    public int size(){
        if(isEmpty()) return 0;
        Node now = head.next;
        int cnt = 0;
        while(now != null){
            cnt++;
            now = now.next;
        }
        return cnt;
    }
}

3.使用数组来实现

class MyStack{
    private int maxSize;
    private int top;
    private int[] arr;

    public MyStack(int size){
        maxSize = size;
        top  = -1;//这里top与数字下表直接对应
        arr = new int[size];//初始化数组
    }
    public void push(int data){
        arr[++top] = data;
    }
    public int pop(){
        return arr[top--];//先取当前值,再自减
    }
    public int peek(){
        return arr[top];
    }
    public boolean isEmpty(){
        return top == -1;
    }
    public int size(){
        return top;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值