Reputation: 3
this is the class data members and getters and setters:
class Queue
{
int[] data; //array
int size; //size of array
int counter; //checker if array is fully or impty
int first; // first element of array
int last; // last element of arry
}
fixed size constructor
public Queue(int size) {
data = new int[this.size];
size = this.size;
counter = 0;
first = 0;
last = 0;
}
default constructor
public Queue() { //default constructor
data = new int[10];
size = 10;
counter = 0;
first = 0;
last = 0;
}
enqueing function "push"
public bool Enqueue(int num) {
bool result;
if (counter<size)
{
data[last] = num;
last++;
if(last == size)
last = 0;
counter++;
return result = true
}
else
{
return result = false;
}
return result;
}
dequeueing function "pop"
public int Dequeueing() {
int result=-1;
// I know that i should make this nullable function but (-1) good at this time
if (counter>0)
{
result = data[first];
first++;
if (first==size)
first = 0;
counter--;
}
return result;
}
on the main it is excute the enqueueing good but dequeueing its (first++)and (counter--) but it doesn't delete first input ** **why it doesn't delete (17)
static void Main(string[] args)
{
Queue q1 = new Queue();
q1.Enqueue(17);
q1.Enqueue(20);
q1.Enqueue(25);
q1.Enqueue(15);
q1.Enqueue(14);
q1.Enqueue(13);
q1.Dequeueing();
Console.ReadLine();
}
Upvotes: 0
Views: 61
Reputation: 4394
Your expectation that once you do first++;
and counter--;
, the data[first]
will be deleted is misplaced. Frankly, if it will somehow cause data[first]
to be deleted then rest of your code will not work. What that code does is to simply Dequeue
. The Queue
bounds are marked using first
and last
, with the help of counter
, so only those things need to change and no array element deletion needs to happen
Let me help you understand your code a bit. Your Queue
class is what is called a Circular Queue. In such an implementation, you have the benefit that the amount of storage allocated for the Queue
is "fixed" and determined on construction. This also implies that when you Enqueue
there will be no extra memory requested and when you Dequeue
there will be no memory released.
If you wish to somehow identify an unoccupied slot in the array, you can use special values. For example, making int?[] data
, you can store var item = data[front]; data[front] = null
before Dequeueing
. Or, you can use a routine like GetQueueData
to return all the elements in the Queue
as a separate IEnumerable
public IEnumerable<int> GetQueueData() {
for (int i = first, cnt = 0; cnt < counter; i = (i + 1) % size, ++cnt)
yield return data[i];
}
Upvotes: 1
Reputation: 14672
The array named data will remain in the same state as when you created it as you have not done anything to make this otherwise.
Upvotes: 0