Repository navigation
Expand file tree
/
Copy pathRingQueue.java
More file actions
72 lines (62 loc) · 1.53 KB
/
Copy pathRingQueue.java
File metadata and controls
72 lines (62 loc) · 1.53 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
import static njupt.yyz.Print.*;
import java.util.*;
public class RingQueue<Item> {
private Node last;
int N;
private class Node {
Item item;
Node next;
}
public boolean isEmpty(){
return null == last;
}
public int size(){
return N;
}
public void enqueue(Item item){
Node oldlast = last;
last = new Node();
last.item = item;
if(null == oldlast) last.next = last;
else {
last.next = oldlast.next;
oldlast.next = last;
}
N++;
}
public Item dequeue(){
if(isEmpty())
throw new NoSuchElementException();
Item item = last.next.item;
if(1 == N) last = null;
else last.next = last.next.next;
N--;
return item;
}
public String toString(){
String result = "";
if(isEmpty()) return result;
Node cur = last.next;
while(cur != last){
result += cur.item + "->";
cur = cur.next;
}
result += cur.item;
return result;
}
public static void main(String[] args){
RingQueue<String> rq = new RingQueue<String>();
Scanner s = new Scanner(System.in);
String token;
while(true){
token = s.nextLine();
if(token.equals("exit"))
break;
if(token.equals("-"))
rq.dequeue();
else
rq.enqueue(token);
println(rq);
}
}
}