Here is the scene:
I want to implement queue using array in C.
First, I allocating a memory block (e.g. 4)
Code:
[ ][ ][ ][ ] <-- this is the array
Then I call unshift function that will append the data similar to the push function in
stack.
Code:
unshift(2)
[2][ ][ ][ ]
unshift(3)
[2][3][ ][ ]
unshift(7)
[2][3][7][ ]
unshift(1)
[2][3][7][1]
Ok, after that, I call the shift function that will return the first offset in the array
increased by one.
Code:
[2][3][7][1] <-- initial array
print shift --> output: 2
[ ][3][7][1]
print shift --> output: 3
[ ][ ][7][1]
print shift --> output: 7
[ ][ ][ ][1]
Of course, there is a slow version of the shift function that will return the first offset in the array then do a real shifting (using loop).
Code:
[2][3][7][1] <-- initial array
print shift --> output: 2
[3][7][1][ ]
print shift --> output: 3
[7][1][ ][ ]
print shift --> output: 7
[1][ ][ ][ ]
Nah, the problem is:
I think I would prefer the first shift function because the speed.
1. But from the algorithm above, is there a way to free certain block of memory?
Code:
print shift --> output: 3
[ ][ ][ ][1]
For example, I want to free the memory block index from 0 to 2.
2. How about linked-listed queue? Is there a guarantee for the speed if we are using it to implementing queue?