Reputation: 129
def enqueue(elem: T): Unit = {
A(rear) = elem
rear += 1
size += 1
if (size == 0) {
front = 0
rear = 0
}
if (size == A.length) {
grow()
}
}
I am implementing a queue using an array and I have some problem in enqueue method, but I couldn't figure out where the mistake exactly is. So can you please give me some hints on where I did a mistake. In the code above size is the number of elements in the arrayqueue, grow is the function that doubles the array when it is full. Thank you in advance.
Upvotes: 1
Views: 843
Reputation: 41646
If you are going to test for size == 0
, you should do that first.
It may help you if you document the invariants of your class and the pre-conditions and post-conditions of your methods to ensure that each methods is preserving the key properties of you queue implementation internals. See http://en.wikipedia.org/wiki/Design_by_contract.
An invariant could be something like size is always less or equal to the array length or size >= 0.
Upvotes: 2
Reputation: 29528
You're not telling anything about what gets wrong so this is a shot in the dark, and not discussing the chosen data structure.
The test size == 0
seems useless, the size will not be zero just after an enqueue
. However what you do is telling on what you do when a dequeue happens, likely return the element at front
and increment front
, and decrement size
.
So a few remark
Summary: at the start of enqueue, if rear is at array length, you must
Upvotes: 2