본문 바로가기

알고리즘/해커랭크

[해커랭크] Queue using Two Stacks [JAVA]

문제링크 : www.hackerrank.com/challenges/queue-using-two-stacks/problem

 

Queue using Two Stacks | HackerRank

Create a queue data structure using two stacks.

www.hackerrank.com

공책에 enqueue와 dequeue 과정을 그리다가 자연스럽게 스택 두 개로 데이터의 최소움직임을 가지고 큐를 구현할 방법이 떠올랐다.

스택 하나는 데이터를 받기만 하며, pop이나 front 연산이 발생할 경우만 다른 스택으로 모든 데이터를 옮긴다. 

한쪽 스택에 있는 데이터들을 빼며 다른쪽 스택에 쌓은 데이터이므로

다른쪽 스택의 데이터는 top부터 큐의 순서를 갖는다.

이후 front나 pop의 연산이 들어올 경우 다른쪽 스택의 데이터를 순차적으로 빼거나 출력하면 된다.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    public static class MyStructure{
        Stack<Integer> first = new Stack<Integer>();
        Stack<Integer> second = new Stack<Integer>(); 
        
        void enQueue(int data){
            first.push(data);
        }
        void deQueue(){
            if(second.size()!=0){
                second.pop();
            }else{
                moveAll();
                if(second.size()!=0)
                    second.pop();
            }
        }
        int front(){
            if(second.size()!=0){
                return second.peek();
            }else{
                moveAll();
                return second.peek();
            }
        }
        void moveAll(){
            while(!first.isEmpty()){
                second.push(first.pop());
            }
        }
    }
    public static void main(String[] args) throws Exception{
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        MyStructure ms = new MyStructure();
        for(int i=0;i<N;i++){
            int x = sc.nextInt();
            if(x==1){
                int data = sc.nextInt();
                ms.enQueue(data);
            }else if(x==2){
                ms.deQueue();
            }else{
                System.out.println(ms.front());
            }
        }
    }
}