2

我正在编写 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;
       }
4

1 回答 1

3

从逻辑上讲,您应该--leftininsertLeft()right--in 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;
    }

}
于 2013-02-20T05:44:35.240 回答