首页 > 试题广场 >

由两个栈组成的队列

[编程题]由两个栈组成的队列
  • 热度指数:7530 时间限制:C/C++ 2秒,其他语言4秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
用两个栈实现队列,支持队列的基本操作。

输入描述:
第一行输入一个整数N,表示对队列进行的操作总数。

下面N行每行输入一个字符串S,表示操作的种类。

如果S为"add",则后面还有一个整数X表示向队列尾部加入整数X。

如果S为"poll",则表示弹出队列头部操作。

如果S为"peek",则表示询问当前队列中头部元素是多少。


输出描述:
对于每一个为"peek"的操作,输出一行表示当前队列中头部元素是多少。
示例1

输入

6
add 1
add 2
add 3
peek
poll
peek

输出

1
2

备注:
1<=N<=1000000

-1000000<=X<=1000000

数据保证没有不合法的操作
import java.util.Scanner;
import java.util.Stack;

public class Main {


    public static void main(String[] args) {

        Queue<Integer>  queue = new Queue<Integer>();

        Scanner scanner = new Scanner(System.in);
        int n = Integer.valueOf(scanner.nextLine());
        String string;
        for (int i = 0; i < n; i++) {
            string = scanner.nextLine();
            if (string.equals("poll")) {
                queue.poll();
            } else if (string.equals("peek")) {
                System.out.println(queue.peek());
            } else {
                queue.offer(Integer.valueOf(string.split(" ")[1]));
            }
        }
    }
}

class Queue<T>{
    private Stack<T> in = new Stack<T>();
    private Stack<T> out = new Stack<T>();

    public synchronized boolean offer(T item) {
        in.push(item);
        return true;
    }


    public synchronized T poll() {

        if (!out.empty()) {
            return out.pop();
        }

        if (in.empty()) {
            return null;
        }

        while (!in.empty()) {
            T t = in.pop();
            out.push(t);
        }

        return out.pop();
    }

    public synchronized T peek(){

        if (!out.empty()) {
            return out.peek();
        }

        if (in.empty()) {
            return null;
        }

        while (!in.empty()) {
            T t = in.pop();
            out.push(t);
        }

        return out.peek();
    }

}

发表于 2021-03-21 07:48:57 回复(0)
import java.util.*;
import java.io.*;
import java.math.*;

/*
    实现一个特殊功能的栈,在实现栈的基本功能的基础上,再实现返回栈中最小元素的操作。
*/
public class Main{
    
    public static void main(String[] args) {
        InputReader inputReader = new InputReader();
        PrintWriter printWriter = new PrintWriter(System.out);
        inputReader.nextLine();  // 输入
        int size = inputReader.nextInt(); // 将 String --> int
        TwoStackQueue stack = new TwoStackQueue();

        for (int i = 0; i < size; i++){
            inputReader.nextLine(); // 读取一行
            String operate = inputReader.next();

            if ("add".equals(operate)){
                Integer num = inputReader.nextInt();
                stack.add(num);
            }
            if ("poll".equals(operate)){
                stack.poll();
            }
            if ("peek".equals(operate)){
                printWriter.println(stack.peek());
            }
        }
        printWriter.close();
    }
    
}
 class TwoStackQueue{
    public Stack<Integer> stackPush;
    public Stack<Integer> stackPop;
    
    public TwoStackQueue(){
        stackPush=new Stack<Integer>();
        stackPop=new Stack<Integer>();
    }
    private void pushToPop(){
        if (stackPop.empty()){
            while(!stackPush.empty()){
                stackPop.push(stackPush.pop());
            }
        }
    }
     public void add(int pushInt){
         stackPush.push(pushInt);
         pushToPop();
     }
    public int poll(){
        if(stackPop.empty()&&stackPush.empty()){
            throw new RuntimeException("Your queue is empty.");
        }
        pushToPop();
        return stackPop.pop();
    }
    
    public int peek(){
        if(stackPop.empty()&&stackPush.empty()){
            throw new RuntimeException("Your queue is empty.");
        }
        pushToPop();
        return stackPop.peek();
    }
}
class InputReader{
    BufferedReader buf; // 缓冲字符流
    StringTokenizer tok;

    InputReader(){
        // InputStreamReader inputStreamReader = new InputStreamReader(System.in);
        // buf = new BufferedReader(inputStreamReader);
        buf = new BufferedReader(new InputStreamReader(System.in));
    }

    boolean hasNext(){
        // 为什么用while 而不用if?? 这里在多线程唤醒那里也遇到了
        while (tok == null || !tok.hasMoreElements()){
            return false;
        }
        return true;
    }
    // 从缓存中读入一行字符串
    void nextLine(){
        try {
            // 创建一个解析给定字符流的tokenizer。
            tok = new StringTokenizer(buf.readLine());
        } catch (Exception e) {
            tok = null;
        }
    }
    String next(){
        if(hasNext()){
            return tok.nextToken();
        }
        return null;
    }
    /*
        数据类型转换
        String --> int,long,double,BigInteger,BigDecimal
     */
    int nextInt(){
        return Integer.parseInt(next());
    }
    long nextLong(){
        return Long.parseLong(next());
    }
    double nextDouble(){
        return Double.parseDouble(next());
    }
    BigInteger nextBigInteger(){
        // 将BigInteger的十进制字符串表示形式转换为BigInteger。
        return new BigInteger(next());
    }
    BigDecimal nextBigDecimal(){
        //将BigDecimal的字符串表示 BigDecimal转换为 BigDecimal 。
        return new BigDecimal(next());
    }
}

发表于 2020-11-03 16:14:18 回复(0)

问题信息

上传者:小小
难度:
2条回答 6088浏览

热门推荐

通过挑战的用户

查看代码