鱼C论坛

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

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

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

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

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

x
7.jpg

  1. class MyStack {

  2.     /** Initialize your data structure here. */
  3.    
  4.     Queue <Integer> data = new LinkedList<Integer>();
  5.    
  6.     public MyStack() {
  7.         
  8.     }
  9.    
  10.     /** Push element x onto stack. */
  11.     public void push(int x) {
  12.         
  13.         Queue <Integer> temp_queue = new LinkedList<Integer>();
  14.         
  15.         temp_queue.offer(x);
  16.         
  17.         while(!data.isEmpty()){
  18.             
  19.             temp_queue.offer(data.peek());
  20.             
  21.             data.poll();
  22.         }
  23.         
  24.         while(!temp_queue.isEmpty()){
  25.             
  26.             data.add(temp_queue.peek());
  27.             
  28.             temp_queue.poll();
  29.         }
  30.         
  31.     }
  32.    
  33.     /** Removes the element on top of the stack and returns that element. */
  34.     public int pop() {
  35.         
  36.         int num = data.peek();
  37.         
  38.         data.poll();
  39.         
  40.         return num;
  41.         
  42.     }
  43.    
  44.     /** Get the top element. */
  45.     public int top() {
  46.         
  47.         return data.peek();
  48.         
  49.     }
  50.    
  51.     /** Returns whether the stack is empty. */
  52.     public boolean empty() {
  53.         
  54.         return data.isEmpty();
  55.         
  56.     }
  57. }

  58. /**
  59. * Your MyStack object will be instantiated and called as such:
  60. * MyStack obj = new MyStack();
  61. * obj.push(x);
  62. * int param_2 = obj.pop();
  63. * int param_3 = obj.top();
  64. * boolean param_4 = obj.empty();
  65. */
复制代码

本帖被以下淘专辑推荐:

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

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-4-29 01:37

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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