Queue Class/ IsEmpty method
So far all this does (at least I hope so lol) is
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 e开发者_高级运维mpty 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;
}
}
So I guess what my question is, abiding by the normal Queue thinking (First in First out) how do I get it to stop? I keep getting an index out of range error.
Are you trying to reinvent the wheel?
Why not use: system.collections.queue?
http://msdn.microsoft.com/en-us/library/system.collections.queue.aspx
And if your just want to do so, Try Reflector on system.collections.queue and see what's inside.
At first glance I suspect you are getting an IndexOutOfRange exception on your Dequeue function which has no limit on the front
variable, it just keeps incrementing on each call and will eventually exceed the array length.
A queue structure is normally implemented as a circular buffer. Take a look here for more details that might help you with your implementation.
http://en.wikipedia.org/wiki/Circular_buffer
You have a finite array and are expecting infinite capacity. An array isn't the best container for this, you should use something else to implement your queue, like the List container.
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; }
精彩评论