我正在写Deque,可以在Front和Rear中添加和删除....我认为我的逻辑错了,但我无法弄清楚!因为当我从前面插入它必须从后面移除,但也从前面移除。 你会检查我的代码并帮助我吗?
public void insertLeft(long j)
{//have to make sure it is not full before inserting
if (!isFull())
if(left == maxSize-1)
left = -1;
queArray[++left] = j;
nItems++;
}
public long removeRight()
{
//make sure it is not empty first
if(!isEmpty())
if(right == maxSize)
right = 0;
nItems--;
long temp = queArray[right++];
// need to increment front after you remove an item
return temp;
}
public void insertRight(long i) {
if (!isFull())
if(right == maxSize-1)
right = 0;
queArray[++right] = i;
nItems++;
}
public long removeLeft(){
if (!isEmpty())
temp = queArray[++left];
if (left == maxSize-1)
left = -1;
nItems--;
return temp;
}
答案 0 :(得分:3)
逻辑上,您应--left
中的insertLeft()
和right--
中的removeRight()
。此代码中还存在一些其他小问题。以下代码工作正常。
public class Deque {
private long[] queArray;
private int maxSize;
private int nItems;
private int left;
private int right;
private boolean isEmpty() { return nItems == 0; }
private boolean isFull() { return nItems == maxSize; }
public Deque(int maxSize) {
this.maxSize = maxSize;
queArray = new long [maxSize];
nItems = 0;
left = 0;
right = maxSize - 1;
}
public void insertLeft(long j) {
if (isFull())
throw new RuntimeException("It is full");
if (left == 0)
left = maxSize;
queArray[--left] = j;
nItems++;
}
public void insertRight(long i) {
if (isFull())
throw new RuntimeException("It is full");
if (right == maxSize - 1)
right = -1;
queArray[++right] = i;
nItems++;
}
public long removeLeft() {
if (isEmpty())
throw new RuntimeException("It is empty");
long temp = queArray[left];
left++;
if (left == maxSize - 1)
left = -1;
nItems--;
return temp;
}
public long removeRight() {
if (isEmpty())
throw new RuntimeException("It is empty");
long temp = queArray[right];
right--;
if (right < 0)
right = maxSize - 1;
nItems--;
return temp;
}
}