2011-04-10 109 views
1

到目前为止,这一切都(至少我希望如此笑)是队列类/为IsEmpty方法

class Queue 
{ 

    private int front = 0; //Creates front and back int holders and an array 
    private int back = -1; 
    private int[] anArray; 

    public Queue(int size) // constructor to get the Queue size 
    { 
     anArray = new int[size]; 
    } 

    public bool IsFull 
    { 
     get // gets to see if the Queue is full (I assume I did this right, It's full if the back of the queue is equal to -1 of an array) 
     { 
      return back == anArray.Length - 1; 
     } 
    } 

    public bool IsEmpty 
    { 
     get // It's empty if the back is -1; I think this is where I messed up, I think that when it checks to see if it's empty it also doesn't check if it's empty when I have dequeued the other numbers (or write them off). Would I make something like "Return front == anArray.Length -1;" ? That would check to see when the front (The part being written to console first) hits the end of the array? 
     { 
      return back == -1; 
     } 
    } 

    public void Enqueue(int valueEnqueue) 
    { // Method to Enqueue the variables into the array 

     if (IsFull) 
     { 
      //do nothing 
     } 
     else 
     { 
      back = back + 1; 
      anArray[back] = valueEnqueue; 

     } 
    } 

    public int Dequeue() 
    { // Method to dequeue the variables put in 
     if (IsEmpty) 
     { 
      //do nothing 
      return 1010101010; 
     } 
     else 
     { 
      int dequeue = anArray[front]; 
      front = front + 1; 
      return dequeue; 
     } 
    } 

所以我想我的问题是什么,通过正常的队列思维守法(先入先出)如何我能让它停下来吗?我一直在索引超出范围错误。

+0

140列的行不太可读。请分解它。 – 2011-04-10 19:22:04

+0

这是如何不可读的?我跳过了几行,等等。 – Nogg 2011-04-10 19:22:43

+0

你不是很接近,这比堆栈更像堆栈。你必须使用[家庭作业]标签来获得你需要的帮助。 – 2011-04-10 19:23:21

回答

0

乍一看,我怀疑你的Dequeue函数中有一个IndexOutOfRange异常,它对front变量没有限制,只是在每次调用时都会增加,最终会超出数组长度。

队列结构通常实现为循环缓冲区。在这里看看更多的细节可能会帮助你实现。

http://en.wikipedia.org/wiki/Circular_buffer

+0

对,这是我在我的伪代码中。我是巨型圈子。我只是困惑如何操作? – Nogg 2011-04-10 19:24:55

+0

@Nog,你的代码并没有实现一个循环缓冲区,因为当数组到达最后时,前端/后端应该环绕到数组的起始位置,例如当前正在增加。看看我链接到的维基百科文章。 – 2011-04-10 19:27:17

+0

所以我应该改变IsFull方法中的某些内容来说明它何时已经满了以启动计数器了吗? – Nogg 2011-04-10 21:18:45

1

你们是不是要推倒重来?

为什么不使用:system.collections.queue

http://msdn.microsoft.com/en-us/library/system.collections.queue.aspx

如果你只是想这样做,尝试反射上system.collections.queue,看看里面有什么。

+1

我猜这是作业。 – 2011-04-10 19:26:29

+0

@Tyler:+1。看起来像这样。 – 2011-04-10 19:28:31

+0

@你们俩,查看我原帖的评论。 – Nogg 2011-04-10 19:33:04

0

你有一个有限的数组,并期待着无限的容量。一个数组不是最好的容器,你应该使用别的方法来实现你的队列,比如List容器。

Enqueue(item) { list.Add(item); } 
Dequeue() 
{ 
    if(!IsEmpty) 
    { 
    var item = list[0]; 
    list.Remove(item); 
    return item; 
    } 
    return null; 
} 
IsFull{ get { return false; } } 
IsEmpty{ get { return list.Count == 0; }