코딩테스트

[JAVA] BFS 넓이 우선 탐색 Stack 으로 구현

dackyy 2022. 7. 30. 23:18
반응형
import java.util.Stack;

class QueueStack {
    Stack<Integer> oldStack;
    Stack<Integer> newStack;

    public QueueStack() {
        oldStack = new Stack<>();
        newStack = new Stack<>();
    }

    public void enqueue(int a) {
        oldStack.push(a);
    }

    public int dequeue() {
        int result = -1;

        if(newStack.isEmpty()) {
            while(!oldStack.isEmpty()) {
                newStack.push(oldStack.pop());
            }
            result = newStack.pop();
        }

        // 남아있으면 돌려주기
        if(!newStack.isEmpty()) {
            while(!newStack.isEmpty()) {
                oldStack.push(newStack.pop());
            }
        }

        return result;
    }
}

public class QueueStackMain {
    public static void main(String[] args) {
        QueueStack a = new QueueStack();
        a.enqueue(1);
        a.enqueue(2);
        a.enqueue(3);

        System.out.println(a.dequeue());
        System.out.println(a.dequeue());
        System.out.println(a.dequeue());
    }
}
class Index {
    private int x;
    private int y;

    public Index() {
    }

    public Index(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }
    public void setX(int x) {
        this.x = x;
    }
    public int getY() {
        return y;
    }
    public void setY(int y) {
        this.y = y;
    }
}
반응형