到目前为止,这一切(至少我希望如此lol)是
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 :(得分:1)
你想重新发明轮子吗?
为什么不使用: system.collections.queue ?
http://msdn.microsoft.com/en-us/library/system.collections.queue.aspx
如果您只是想这样做,请在system.collections.queue上尝试 Reflector ,看看里面是什么。
答案 1 :(得分:0)
乍一看,我怀疑你的Dequeue函数有一个IndexOutOfRange异常,它对front
变量没有限制,它只是在每次调用时都会递增,最终会超出数组长度。
队列结构通常实现为循环缓冲区。请查看此处了解可能有助于您实施的更多详细信息。
答案 2 :(得分: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; }