-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueuePractice.java
More file actions
97 lines (78 loc) · 2.23 KB
/
Copy pathQueuePractice.java
File metadata and controls
97 lines (78 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package dataStructure.linear.queue;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.stream.IntStream;
class ArrayQueue {
int[] arr;
int front;
int rear; // 첫 front를 비워둬야 함.
public ArrayQueue(int length) {
this.arr = new int[length+1];
}
private boolean isFull() {
return front == (rear + 1) % arr.length;
}
public boolean isEmpty() {
return front == rear;
}
public void add(int num) {
if (isFull()) {
System.out.println("Full");
} else {
rear = (rear+1)%arr.length;
arr[rear] = num;
}
}
public void delete() {
if(isEmpty())
System.out.println("empty");
else
front = (front+1)%arr.length;
}
public void printQ() {
System.out.print("q = ");
for (int i = (front+1)%arr.length; i != (rear+1)%arr.length; i = (i+1)%arr.length) {
System.out.print(this.arr[i]+" ");
}
System.out.println();
}
}
public class QueuePractice {
static int solution(int n) {
Queue<Integer> q = new LinkedList<>();
for (int i = 1; i <= n; i++) {
q.add(i);
}
while (q.size() > 1) {
q.remove();
q.add(q.poll());
System.out.println(q);
}
return q.peek();
}
static ArrayList solution2(int n,int k) {
ArrayList<Integer> result = new ArrayList<>();
Queue<Integer> q = new LinkedList<>();
IntStream.range(1, n + 1).forEach(i -> q.add(i));
int count = 1;
while (!q.isEmpty()) {
if (count == k) {
result.add(q.remove());
} else {
q.add(q.remove());
}
count = count % k + 1;
}
System.out.println(result);
return result;
}
public static void main(String[] args) {
Queue queue = new LinkedList(); // queue는 인터페이스고 linkedlist에 구현돼있음
// System.out.println(solution(4));
// System.out.println(solution(7));
// System.out.println(solution(9));
solution2(5, 2);
solution2(7, 3);
}
}