본문 바로가기

Algorithms/Cracking the Coding Interview

Queues: A Tale of Two Stacks

queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out(FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed.

A basic queue has the following operations:

  • Enqueue: add a new element to the end of the queue.
  • Dequeue: remove the element from the front of the queue and return it.

In this challenge, you must first implement a queue using two stacks. Then process  queries, where each query is one of the following  types:

  1. 1 x: Enqueue element  into the end of the queue.
  2. 2: Dequeue the element at the front of the queue.
  3. 3: Print the element at the front of the queue.

Input Format

The first line contains a single integer, , denoting the number of queries. 
Each line  of the  subsequent lines contains a single query in the form described in the problem statement above. All three queries start with an integer denoting the query , but only query  is followed by an additional space-separated value, , denoting the value to be enqueued.

Constraints

  • It is guaranteed that a valid answer always exists for each query of type .

Output Format

For each query of type , print the value of the element at the front of the queue on a new line.

Sample Input

10
1 42
2
1 14
3
1 28
3
1 60
1 78
2
2

Sample Output

14
14

Explanation

We perform the following sequence of actions:

  1. Enqueue .
  2. Dequeue the value at the head of the queue, .
  3. Enqueue .
  4. Print the value at the head of the queue, .
  5. Enqueue .
  6. Print the value at the head of the queue, .
  7. Enqueue .
  8. Enqueue .
  9. Dequeue the value at the head of the queue, .
  10. Dequeue the value at the head of the queue, .


풀이


Stack에 있는 다른 메소드를 이용해서 (ex: insertElementAt(value, index) 같은) 쉽게 할 수 있는데


두 개의 stack으로 queue를 구현하는게 목적


import java.io.*;

import java.util.*;

import java.text.*;

import java.math.*;

import java.util.regex.*;


public class Solution {

    public static class MyQueue<T> {

        Stack<T> stackNewestOnTop = new Stack<T>();

        Stack<T> stackOldestOnTop = new Stack<T>();


        public void enqueue(T value) { // Push onto newest stack

            stackOldestOnTop.push(value);

        }


        public T peek() {

            if(stackNewestOnTop.isEmpty()){

                while(!stackOldestOnTop.isEmpty())

                    stackNewestOnTop.push(stackOldestOnTop.pop());

                }

            return stackNewestOnTop.peek();

        }


        public T dequeue() {

            if(stackNewestOnTop.isEmpty()){

                while(!stackOldestOnTop.isEmpty())

                    stackNewestOnTop.push(stackOldestOnTop.pop());

            }

            return stackNewestOnTop.pop();

        }

    }


    

    public static void main(String[] args) {

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

        

        Scanner scan = new Scanner(System.in);

        int n = scan.nextInt();

        

        for (int i = 0; i < n; i++) {

            int operation = scan.nextInt();

            if (operation == 1) { // enqueue

                queue.enqueue(scan.nextInt());

            } else if (operation == 2) { // dequeue

                queue.dequeue();

            } else if (operation == 3) { // print/peek

                System.out.println(queue.peek());

            }

        }

        scan.close();

    }

}

'Algorithms > Cracking the Coding Interview' 카테고리의 다른 글

Sorting: Bubble Sort  (0) 2018.04.04
Heaps: Find the Running Median  (0) 2018.03.23
Stacks: Balanced Brackets  (0) 2018.02.19
Linked Lists: Detect a Cycle  (0) 2018.02.19
Hash Tables: Ransom Note  (0) 2018.02.09