-
Notifications
You must be signed in to change notification settings - Fork 0
/
CircularQueue.java
116 lines (99 loc) · 2.51 KB
/
CircularQueue.java
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import java.util.Iterator;
import java.util.NoSuchElementException;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Tony
* @param <Item>
*/
public class CircularQueue<Item> implements Iterable<Item> {
private static int N, M, sz;
private Node first, last;
public CircularQueue() {
first = null;
last = null;
sz = 0;
}
private class Node {
Item item;
Node next;
}
public boolean isEmpty() {
return first == null;
}
public int size() {
return sz;
}
/**
* Add item to the end of the list
* @param item
*/
public void enqueue(Item item) {
Node oldlast = last;
last = new Node();
last.item = item;
last.next = null;
if(isEmpty())
first = last;
else
oldlast.next = last;
sz++;
}
/**
* Remove item from the beginning of the list
* @return
*/
public Item removeFirst() {
Item item = first.item;
first = first.next;
sz--;
if(isEmpty())
last = null;
return item;
}
/**
*
* @return
*/
@Override
public Iterator iterator() {
return new ListIterator<>(first);
}
private class ListIterator<Item> implements Iterator<Item> {
private Node current;
public ListIterator(Node first) {
current = first;
}
@Override
public boolean hasNext() {
return current != null;
}
@Override
public void remove() { throw new UnsupportedOperationException(); }
@Override
public Item next() {
if (!hasNext()) throw new NoSuchElementException();
Item item = (Item) current.item;
current = current.next;
return item;
}
}
public static void main(String[] args) {
N = Integer.valueOf(args[0]);
M = Integer.valueOf(args[1]);
CircularQueue q = new CircularQueue();
for (int i=0; i<N; i++)
q.enqueue(i);
Iterator itr = q.iterator();
while (itr.hasNext() && sz != 0) {
for (int i=0; i<M-1; i++) {
q.enqueue(q.removeFirst());
}
StdOut.print(q.removeFirst() + " ");
}
}
}