-1
我已經編寫了自己的Java隊列實現。我正在排隊1-20,然後我想按照正確的順序將他們排隊。然而,我只得到0號碼,這讓我覺得我的問題出現在我的排隊,出隊或移動方法中。隊列實現不正確出隊
class Queue {
private int size = 8;
public static final int DEFAULT_CAPACITY = 8;
private int[] elements = new int[size];
public Queue() {
this(DEFAULT_CAPACITY);
}
public Queue(int size) {
elements = new int[size];
}
public void enqueue(int v) {
if(size==elements.length) {
DoubleSize();
}
v=elements[size];
size++;
}
public int dequeue() {
int removed=elements[0]
move();
return removed;
}
//double capacity called in enqueue
private void DoubleSize() {
int[] test=new int[this.elements.length*2];
for(int i=0;i<test.length;i++) {
if(i<this.elements.length) {
test[i]=this.elements[i];
} else {
test[i]=0;
}
}
this.elements=test;
}
//moving values called in dequeue
private void move() {
int position = size;
for (int i = position-1; i >= 1; i--) {
elements[i+1] = elements[i];
}
}
public boolean empty() {
if(elements[0]==0) {
return true;
} else {
return false;
}
}
public int getSize() {
return size;
}
}
這裏是測試程序
class TestQueue {
public static void main (String[] args) {
Queue queue = new Queue();
for(int i=1;i<=20;i++) {
queue.enqueue(i);
}
for(int i=1;i<=20;i++) {
System.out.print(queue.dequeue() + " ");
}
}
}
我應該如何解決...我應該添加另一個變量嗎? – Becca 2014-12-07 20:37:19