我的任務是在java中創建一個Deque,使用選項添加左邊,添加右邊,刪除左邊並刪除右邊。移除出隊前端的問題(雙端隊列)
我已經編寫了添加權限,併成功地刪除了正確的方法,但我有問題試圖讓左側添加和刪除左側工作。
我覺得我已經大大地錯了某個地方。我剛纔想換輪變量左側添加和倒車,沒有工作,而且只會拿出以下的計算:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:3332)
at java.lang.AbstractStringBuilder.expandCapacity(AbstractStringBuilder.java:137)
at java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:121)
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:421)
at java.lang.StringBuffer.append(StringBuffer.java:265)
at datastructuresass1.DendQueue.toString(DendQueue.java:107)
at datastructuresass1.main.main(main.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
我試圖創建一個使用數組雙端隊列。下面是我的代碼的權限添加並添加左方法:
添加左(沒有工作)
public void addLeft(T o){
left = (left + 1) % arr.length;
arr[left] = o;
// if the array is full copy it to a larger one
if ((left + 1) % arr.length == right) {
T[] newarr = (T[]) new Object[arr.length * 2];
int i;
for (i = 0; i < arr.length; i++)
newarr[i] = arr[(right - i) % arr.length];
arr = newarr;
left = i - 1;
right = 0;
System.out.println("Array size increased to " +
arr.length);
}
添加右鍵(這是工作)
public void addRight(T o) {
right = (right + 1) % arr.length;
arr[right] = o;
// if the array is full copy it to a larger one
if ((right + 1) % arr.length == left) {
T[] newarr = (T[]) new Object[arr.length * 2];
int i;
for (i = 0; i < arr.length; i++)
newarr[i] = arr[(left + i) % arr.length];
arr = newarr;
left = 0;
right = i - 1;
System.out.println("Array size increased to " +
arr.length);
}
請能有人解釋對我來說爲什麼這個addLeft方法不起作用。這將是一個很大的幫助,因爲我一直在這個難住!提前致謝。