鱼C论坛

 找回密码
 立即注册
查看: 2043|回复: 0

[学习笔记] leetcode 225. Implement Stack using Queues

[复制链接]
发表于 2019-8-6 07:34:11 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
7.jpg
class MyStack {

    /** Initialize your data structure here. */
    
    Queue <Integer> data = new LinkedList<Integer>();
    
    public MyStack() {
        
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        
        Queue <Integer> temp_queue = new LinkedList<Integer>();
        
        temp_queue.offer(x);
        
        while(!data.isEmpty()){
            
            temp_queue.offer(data.peek());
            
            data.poll();
        }
        
        while(!temp_queue.isEmpty()){
            
            data.add(temp_queue.peek());
            
            temp_queue.poll();
        }
        
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        
        int num = data.peek();
        
        data.poll();
        
        return num;
        
    }
    
    /** Get the top element. */
    public int top() {
        
        return data.peek();
        
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        
        return data.isEmpty();
        
    }
}

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * boolean param_4 = obj.empty();
 */

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-21 14:03

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表