侧边栏壁纸
博主头像
惊羽博主等级

hi ,我是惊羽,前生物学逃兵,现系统工程沉迷者 . 贝壳签约工程师 , 曾被雇佣为 联拓数科 · 支付研发工程师 、京东 · 京东数科 · 研发工程师、中国移动 · 雄安产业研究院 · 业务中台技术负责人 .

  • 累计撰写 102 篇文章
  • 累计创建 14 个标签
  • 累计收到 14 条评论

算法练习(15) - 两个队列实现栈

惊羽
2021-06-24 / 0 评论 / 0 点赞 / 170 阅读 / 920 字
温馨提示:
本文为原创作品,感谢您喜欢~

题目

请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通队列的全部四种操作(push、top、pop 和 empty)。

思路

队列(FIFO) , 先进先出,那么只要使用一个空的 临时队列 offer()最新的元素,然后将 原队列的数据 offer()到临时队列,这样,临时队列中的顺序就是最后进来的反而成了最先进来的,也就是说临时队列 pop() 出去的就是最新的元素,那么再互换 临时队列 和原队列的指针,就得到了正确的队列;

题解

import java.util.LinkedList;

class MyStack {

    LinkedList<Integer> data ;
    LinkedList<Integer> revers ;
    LinkedList<Integer> temp ;

    /** Initialize your data structure here. */
    public MyStack() {
         data = new LinkedList<>();
        revers = new LinkedList<>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        if (data.isEmpty()){
            data.offer(x);
        }else{
            if(!data.isEmpty()){
                revers.offer(x);
            }
            while(!data.isEmpty()){
                revers.offer(data.pop());
            }
            temp = revers;
            revers = data;
            data = temp;
        }
        System.out.println(data);
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return data.pop();
    }
    
    /** Get the top element. */
    public int top() {
        return  data.getFirst();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return   data.isEmpty();
    }
}
0
广告 广告

评论区