面试Java手写实现堆栈

面试时,面试官要求手写双链表,然后使用实现的双链表实现栈,不能使用jdk已提供的集合。

贴代码,欢迎大家点评

1.链表元素类实现

/**
 * 链表元素类
 */
class Node{
    private Node pre;
    private Node next;
    private Object value;

    public Node() {
    }

    public Node(Object value) {
        this.value = value;
    }

    public Node(Node pre, Node next, Object value) {
        this.pre = pre;
        this.next = next;
        this.value = value;
    }

    public Node getPre() {
        return pre;
    }

    public void setPre(Node pre) {
        this.pre = pre;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }

    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }
}

2.栈实现

/**
 * 栈
 */
class Stack{
     private Node top;
     private Integer length = 0;
    public synchronized void  push(Node e){
        if(!Objects.isNull(top)){
            //新增节点前驱指针指向,当前节点
            e.setPre(top);
            //当前节点的后继指针指向,新增节点
            top.setNext(e);
            //设置当前节点为栈顶
            top = top.getNext();
        }else{
            //边界处理
            top = e;
        }
        length++;
    }
    public synchronized Node pop(){
        Node tmp = new Node();
        while (top.getNext() == null){
            tmp.setValue(top.getValue());

            top = top.getPre();
            if(top == null){
                length--;
                return tmp;
            }
            //前驱指针置空
            top.getNext().setPre(null);
            //后驱指针置空
            top.setNext(null);
            //栈深减一
            length--;
            return tmp;
        }
        return tmp;
    }

    public Integer getLength() {
        return length;
    }
}

3.测试类

public static void main(String[] args) {
        Stack stack = new Stack();
        for(int i=0 ; i < 3 ; i++){
            stack.push(new Node(new Integer(i)));
        }
        int len = stack.getLength();
        for(int i=0 ; i<len ; i++){
            System.out.println(stack.pop());
        }
    }

输入顺序0,1,2

输出结果

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值