package com.queueapi;
/**
* Created by Dhaval on 6/15/2016.
*/
public class DynamicArrayQueue {
private String[] s;
private int head = -1;
private int tail = -1;
public DynamicArrayQueue() {
}
public boolean isEmpty() {
return head == -1 || head > tail || s.length == 0;
}
public void enqueue(String item) {
if (isEmpty()) {
head = 0;
tail = 0;
s = new String[1];
}
if (tail - head == s.length) {
resize(s.length * 2);
}
s[tail++] = item;
}
public String dequeue() throws QueueUnderFlowException {
if (isEmpty()) {
throw new QueueUnderFlowException();
}
String item = s[head++];
if (tail - head == s.length/4) {
resize(s.length/2);
}
return item;
}
public void resize(int capacity) {
String[] copy = new String[capacity];
for (int i = head; i < tail; i++) {
copy[i - head] = s[i];
}
s = copy;
tail = tail - head;
head = 0;
}
}
私は、3つの基本的な機能をサポート配列を使用して動的にサイズ変更可能なキューを実装しようとしています:実装キューAPIの使用サイズ変更可能な配列
isEmpty()
Enqueue()
Dequeue()
制約は、キューのshou ldは常に25-100%の範囲内で塗りつぶされます。したがって、キューがいっぱいになると配列のサイズを2倍に変更し、キューの要素数がsize/4に等しい場合はサイズをsize/2に減らします。
このキューは、次のように入力を受け付けるテスタとともに使用されます。 1 - 2 - 3ここで、 " - "が発生するとdequue()操作が実行され、そうでない場合はenqueue()が実行されます。
コードが1 2 3 - - - - 入力として失敗しています。私がどこに間違っているのか、いくつかの洞察を教えてください。あなたの問題の場合は
テスタークライアント
package com.queueapi;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
public class QueueTester {
public static void main(String[] args) throws QueueUnderFlowException {
DynamicArrayQueue queue = new DynamicArrayQueue();
while(!StdIn.isEmpty()){
String s = StdIn.readString();
if(s.equals("-")){
StdOut.print(queue.dequeue());
}
else{
queue.enqueue(s);
}
}
}
}
「失敗している」とはどういう意味ですか? – awksp
まあ、期待される出力は 'QueueUnderFlowException'でしょう - どの出力を得ますか? –
テスターのクラスコードを投稿してください。失敗すると、例外や予期しない動作が発生しますか? – Saravana