2013-02-20 123 views
2

我写Deque能够添加和从前后两个删除....我认为我的逻辑是错误的,但我无法弄清楚!因为当我从前面插入它必须从后面删除,但也从前面删除。 你会检查我的代码,并帮助我吗?Deque在前面插入并从后面删除

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; 
     } 

回答

3

从逻辑上讲,你应该--leftinsertLeft()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; 
    } 

} 
+0

的insertLeft()工作正常,但我insertRight并删除左还是一样:(谢谢尽管 – NilR 2013-02-20 05:49:32

+0

太谢谢你了它的工作prety很好,但我为什么要--left的左++,而不是? – NilR 2013-02-20 06:33:38

+1

'left'和'right'之间的数字是deque中的元素,通过在左端插入一些东西,您需要使用' - left'来增大范围 – Jiangzhou 2013-02-20 13:22:28