• 【LeetCode225】 Implement Stack using Queues★


    1.题目

    2.思路

    3.java代码

     1 import java.util.LinkedList;
     2 import java.util.Queue;
     3 
     4 public class MyStack {
     5     private Queue<Integer> q1=new LinkedList<Integer>();
     6     private Queue<Integer> q2=new LinkedList<Integer>();
     7     
     8     /** Push element x onto stack. */
     9     public void push(int x) {
    10         if(!q1.isEmpty())
    11             q1.add(x);
    12         else
    13             q2.add(x);
    14     }
    15     
    16     /** Removes the element on top of the stack and returns that element. */
    17     public int pop() {
    18         if(q1.isEmpty()){
    19             int size=q2.size();
    20             for(int i=1;i<size;i++){
    21                 q1.add(q2.poll());
    22             }
    23             return q2.poll();
    24         }else{
    25             int size=q1.size();
    26             for(int i=1;i<size;i++){
    27                 q2.add(q1.poll());
    28             }
    29             return q1.poll();
    30         }
    31     }
    32     
    33     /** Get the top element. */
    34     public int top() {
    35         int result;
    36         if(q1.isEmpty()){
    37             int size=q2.size();
    38             for(int i=1;i<size;i++){
    39                 q1.add(q2.poll());
    40             }
    41             result=q2.poll();
    42             q1.add(result);
    43         }else{
    44             int size=q1.size();
    45             for(int i=1;i<size;i++){
    46                 q2.add(q1.poll());
    47             }
    48             result=q1.poll();
    49             q2.add(result);
    50         }
    51         return result;
    52     }
    53     
    54     /** Returns whether the stack is empty. */
    55     public boolean empty() {
    56         return q1.isEmpty()&&q2.isEmpty();
    57     }
    58 }
    59 
    60 /**
    61  * Your MyStack object will be instantiated and called as such:
    62  * MyStack obj = new MyStack();
    63  * obj.push(x);
    64  * int param_2 = obj.pop();
    65  * int param_3 = obj.top();
    66  * boolean param_4 = obj.empty();
    67  */
  • 相关阅读:
    javascript线性渐变2
    javascript无缝滚动2
    javascript Object对象
    javascript无缝滚动
    javascript图片轮换2
    javascript图片轮换
    用C/C++写CGI程序
    linux shell 的 for 循环
    重磅分享:微软等数据结构+算法面试100题全部答案完整亮相
    查看linux服务器硬盘IO读写负载
  • 原文地址:https://www.cnblogs.com/zhangboy/p/6558425.html
Copyright © 2020-2023  润新知