알고리즘/백준 알고리즘(JAVA)
JAVA)1158번 Queue(큐)로 요세푸스 순열 구하기
starmk95
2020. 7. 14. 21:04
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int K = sc.nextInt();
Queue<Integer> queue = new LinkedList<>(); // Queue는 LinkedList 인터페이스를 사용하여 구현되었다.
StringBuilder sb = new StringBuilder();
sb.append("<");
for (int i=0;i<N;i++) {
queue.add(i+1);
}
while (queue.size() > 1) {
for (int i=0;i<K-1;i++) {
int temp = queue.poll();
queue.offer(temp);
}
sb.append(queue.poll() + ", ");
}
sb.append(queue.poll() + ">");
System.out.print(sb);
}
}
Java에서 Queue 자료구조는 LinkedList 인터페이스로 구현되어 있다.
Stack에 pop()과 push()가 있다면, Queue에는 poll()과 offer() 메소드가 있다.
Queue 객체 생성 방법은 다음과 같다.
Queue<자료형> 변수이름 = new LinkedList<>();