题解 | #由两个栈组成的队列#

由两个栈组成的队列

https://www.nowcoder.com/practice/6bc058b32ee54a5fa18c62f29bae9863

import java.util.*;
public class Main {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        myQueue mq = new myQueue();
        int n = Integer.valueOf(sc.nextLine());
        for(int i = 0; i < n; i++) {
            String line = sc.nextLine();
            String[] strs = line.split(" ");
            if(strs[0].equals("add")) {
                mq.add(Integer.parseInt(strs[1]));
            } else if(strs[0].equals("poll")) {
                mq.poll();
            } else if(strs[0].equals("peek")) {
                int t = mq.peek();
                System.out.println(t);
            }
        }
    }
}
class myQueue {
    
    private Stack<Integer> stackIn = new Stack<Integer>();
    private Stack<Integer> stackOut = new Stack<Integer>();
    
    public void myQueue() {
        
    }
    
    public void inToOut() {
        if(stackOut.isEmpty()) {
            while(!stackIn.isEmpty()) {
                stackOut.push(stackIn.pop());
            }
        }
    }
    
    public void add(int X) {
        inToOut();
        stackIn.add(X);
    }
   
    public void poll() {
        if(stackIn.isEmpty() && stackOut.isEmpty()) {
            throw new RuntimeException("error");
        } else if(stackOut.isEmpty()) {
          inToOut();  
        }
        stackOut.pop();
    }
    
    public int peek() {
        if(stackIn.isEmpty() && stackOut.isEmpty()) {
            throw new RuntimeException("error");
        } else if(stackOut.isEmpty()) {
          inToOut();  
        }
        return stackOut.peek();
    }
    
}

解题方法

队列的特点是先进先出,而栈的特点是先进后出,那么使用两个栈,一个压入栈,一个弹出栈,压入栈指用来压入数据,同理弹出栈只用来弹出数据,当弹出栈数据为空而压入栈数据不为空时就将压入栈数据全部转移到弹出栈。

#算法题#
全部评论

相关推荐

点赞 评论 收藏
分享
不放弃的小鱼干很洒脱:好可爱的离职理由
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务