LeetCode255用对列实现栈

方法1:用一个对列实现栈,其实复杂在入队,其他都是直接调用系统方法,入队,如果入队之后,队长度为1,不进行操作,否则,就把刚入队的元素调整到栈顶(队首)其实就是把其余元素在入队,这样构成的对列,始终和栈的结构是一样的

class MyStack {
    LinkedList<Integer> l1=new LinkedList();
    /** Initialize your data structure here. */
    public MyStack() {
        l1=new LinkedList();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        l1.add(x);
        if(l1.size()==0){
            return;
        }
        int length=l1.size()-1;
        while(length>0){
            l1.add(l1.poll());
            length--;
        }
    }
    public int pop() {
        return l1.poll();
    }
    
    /** Get the top element. */
    public int top() {
        return l1.peek();
    }
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return l1.size()==0;
    }
}

方法2:用一个临时对列help,这个重点是出队,每次出队,都要把对列的n-1个元素放到help对列,然后输出最后一个元素,然后交换help和对列的引用,保证每次取元素都是在非help对列,保证代码的可用性。

class MyStack {
    Queue<Integer> qu;
    Queue<Integer> help;
    /** Initialize your data structure here. */
    public MyStack() {
        qu=new LinkedList<Integer>();
        help=new LinkedList<Integer>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
       qu.add(x);
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        while(qu.size()>1){
            help.add(qu.poll());
        }
        int temp=qu.poll();
        swap();
        return temp;
    }
    
    /** Get the top element. */
    public int top() {
        if(qu.size()==1){
            return qu.peek();
        }
        while(qu.size()>1){
            help.add(qu.poll());
        }
        int temp=qu.poll();
        help.add(temp);
        swap();
        return temp;
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return qu.size()==0;
    }
    public void swap(){
        Queue<Integer> temp=qu;
        qu=help;
        help=temp;
    }
}

这里又爆了一个奇葩的错,就是swap参数,如果我传help和qu就会报空指针,这不是引用吗??,为什么就报错呢??/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值