队列类/ IsEmpty方法

本文关键字:方法 IsEmpty 队列 | 更新日期: 2023-09-27 17:49:42

到目前为止,所有这些(至少我希望如此)都是

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

所以我想我的问题是,遵守正常的队列思维(先进先出)我如何让它停止?

队列类/ IsEmpty方法

你是想重新发明轮子吗?

为什么不使用:system.collections.queue?http://msdn.microsoft.com/en-us/library/system.collections.queue.aspx

如果你只是想这样做,尝试Reflector on system.collections.queue,看看里面有什么

乍一看,我怀疑你在Dequeue函数上得到indexoutorange异常,该函数对front变量没有限制,它只是在每次调用时保持递增,最终将超过数组长度。

队列结构通常被实现为一个循环缓冲区。查看这里,了解更多可能对您实现有所帮助的细节。

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

您有一个有限的数组,并期望无限的容量。数组不是最好的容器,你应该使用其他的东西来实现你的队列,比如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; }