0
class CircularQueue{
    private char q[];
    private int putloc, getloc;

    public CircularQueue(int size){
      q = new char[size+1];
      putloc = getloc = 0;
    }

    public void put (char ch) {
      if (putloc+1==getloc | ((putloc ==q.length-1) & (getloc==0))) {
        System.out.println ("Queue is full.");
        return;
      }
      putloc++;
      if(putloc==q.length) putloc = 0;
      q[putloc] = ch;
    }

    public char get() {
      if (getloc == putloc){
        System.out.println("Queue is empty.");
        return (char) 0;
      }

      getloc++;
      if(getloc==q.length) getloc =0;
      return q[getloc];
    }
  }

I don't understand when the queue would be full.

If putloc == q.length-1, it would be at the end of an array.
getloc == 0 would be at the beginning of the array.
So if put() was called it would do putloc++ and go to q[0] and put a value there.
They claim it would overwrite a value at q[0] but if getloc == 0 then that means it already returned a value from that part of the array.
q[getloc] immediately follows getloc++ so once getloc == 0 it will get a value from q[0] leaving that space empty for putting new values.
So the next time get() is called it would get a value from q[1].

Can someone please explain where my logic is wrong?

4

1 回答 1

0

您的主张:“如果getloc == 0那意味着它已经从数组的该部分返回了一个值。” 问题是这并不总是正确的。在put()函数中,你有条件if (putloc+1==getloc || ((putloc ==q.length-1) && (getloc==0)))。如果数组已满,但没有人调用过get(),则((putloc ==q.length-1) && (getloc==0))等于true,不会返回任何值。

另外两件事要解决:

-使用&&and ||,而不是&and |。两个标记表示布尔运算,一个标记用于位操作。
- 编写的这段代码不是线程安全的。如果一个线程同时调用get(),另一个线程同时调用put()getloc和/或putloc将不准确。为了解决这个问题,我会使用synchronized

public void put (char ch) {
    synchronized(q) {
      if (putloc+1==getloc | ((putloc ==q.length-1) & (getloc==0))) {
        System.out.println ("Queue is full.");
        return;
      }
      putloc++;
      if(putloc==q.length) putloc = 0;
      q[putloc] = ch;
   }
}

public char get() {
  synchronized(q) {
      if (getloc == putloc){
        System.out.println("Queue is empty.");
        return (char) 0;
      }

      getloc++;
      if(getloc==q.length) getloc =0;
      return q[getloc];
  }
}
于 2013-09-15T22:34:51.443 回答