Array Queue (陣列)


Queue 的 Array 實作..因為 Array 在 Java 中是使用固定的形式
所以引致了 toString 排序時候出現了兩種可能性..

  1. 是正常的情況..”前者比後者小”..
  2. 是由於固定情況.所以如果資料多了就會在 0 的位置再次填上.

– 這樣會引致了 “後者比前者小”

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
class ArrayQueue {
private int size, head, tail, count;
private Object data[];

public ArrayQueue(int size) {
this.size = size;
this.data = new Object[this.size];
this.head = 0; this.count = 0; this.tail = -1;
}

public boolean full() {
return this.count == this.size;
}

public boolean empty() {
return this.count <= 0;
}

public void enqueue(Object item) throws QueueFullException {
if (this.full()) throw new QueueFullException();

this.count++;

if (this.tail < this.size - 1) {
this.tail++;
}else{
this.tail = 0;
}

this.data[this.tail] = item;
}

public Object dequeue() throws EmptyQueueException {
if (this.empty()) throw new EmptyQueueException();

this.count--;
Object item = this.data[this.head];

if (this.head < this.size - 1) {
this.head++;
}else{
this.head = 0;
}

return item;
}

public String toString() {
String str = "[ ";

/*
基本上有兩個可能性
1. 如果 (尾 >= 頭) 同 (尾 == 陣列大小)
2. 如果 (尾 <= 頭)
*/

// 例外事件
if (this.empty()) return str + "]";

// 情況一
if (this.tail >= this.head && this.tail < this.size) {
// 由 頭 開始迴圈到 尾 (這為正常的情況)
for(int i=this.head; i<=this.tail; i++) {
str += data[i] + " ";
}
}

// 情況二
// 因為固定陣列,所以如果多出的會在位置 0 再重生
// 所以使會出現類似 6 7 _ _ _ _ 4 5
// 而列出的應該是 4 5 6 7
if (this.tail < this.head) {
// 由 頭 開始迴圈到 陣列的大小 (取出頭的資料)
for(int i=this.head; i<this.size; i++) {
str += data[i] + " ";
}

// 由位置 0 開始迴圈到 尾 的位置
for(int i=0; i<=this.tail; i++) {
str += data[i] + " ";
}
}

return str + "]";
}
}

class EmptyQueueException extends RuntimeException {
public EmptyQueueException() {
super("Queue Is Empty");
}
}

class QueueFullException extends RuntimeException {
public QueueFullException() {
super("Queue Is Full");
}
}

經過高人指點後..得到的新方法?

1
2
3
4
5
6
7
8
9
10
11
12
13
public String toString() {
String s = "Head [ ";
int index = this.head;
for (int i = 0; i < this.count; i++) {
s = s + entry[index] + " ";
if (index < this.size - 1)
index++;
else
index = 0;
}
s = s + "] Tail";
return s;
}