zoukankan      html  css  js  c++  java
  • 用两个队列模拟栈的弹出和输入

     1 import java.util.LinkedList;
     2 import java.util.Queue;
     3 
     4 public class StackToQueue {
     5     //用两个队列模拟栈的push 和 pop
     6     Queue<Integer> q1 = new LinkedList<Integer>();
     7     Queue<Integer> q2 = new LinkedList<Integer>();
     8     //移除元素
     9     public int poll(){
    10         if(q1.isEmpty() && q2.isEmpty())//如果两个都为空,返回-1,表示没有元素
    11             return -1;
    12         //如果q1 不为空,那么q1中有元素,将q1中的元素存放入q2中,剩下最后一个
    13         if(!q1.isEmpty() && q2.isEmpty()){
    14             int size = q1.size();
    15             for(int i = 0; i < size; i++){
    16                 if(i == size-1)
    17                     return q1.poll();
    18                 else
    19                     q2.offer(q1.poll());
    20             }
    21         }//相反 同理,q2不为空,那么将q2中的元素放入q1中,剩下最后一个
    22         if(!q2.isEmpty() && q1.isEmpty()){
    23             int size = q2.size();
    24             for(int i = 0; i < size; i++){
    25                 if(i == size-1)
    26                     return q2.poll();
    27                 else
    28                     q1.offer(q2.poll());
    29             }
    30         }
    31         return -1;
    32     }
    33     //加入元素
    34     public void offer(int node){
    35         if(q1.isEmpty() && q2.isEmpty())//如果两个都为空,则添加到队列q1中
    36           q1.offer(node);
    37         else if(!q2.isEmpty() && q1.isEmpty())//如果q2不为空,那么添加到q2中
    38           q2.offer(node);
    39         else if(q2.isEmpty() && !q1.isEmpty())//如果q1不为空,那么添加到q1中
    40           q1.offer(node);
    41     }
    42     public static void main(String[] args) {
    43         StackToQueue sq = new StackToQueue();
    44         sq.offer(5);
    45         sq.offer(4);
    46         sq.offer(3);
    47         System.out.println(sq.poll());
    48         sq.offer(6);
    49         System.out.println(sq.poll());
    50         System.out.println(sq.poll());
    51         System.out.println(sq.poll());
    52         System.out.println(sq.poll());
    53     }
    54 }
  • 相关阅读:
    leetcode目录
    Windows下tuxedo配置
    实习总结
    n人比赛,可轮空,比赛轮数和场数
    Ubuntu中Eclipse安装与配置
    Lunix中文乱码解决方案
    tuxedo入门
    useradd和adduser的区别
    每个位上都是素数
    TUXEDO错误解决方案
  • 原文地址:https://www.cnblogs.com/fankongkong/p/6733632.html
Copyright © 2011-2022 走看看