I am looking at the following two functions of two operations of a queue:
Insert(Q,x)
Q[end[Q]] <- x
if end[Q]=length[Q] then
end[Q] <- 1
else
end[Q] <- end[Q]+1
Delete(Q)
x <- Q[head[Q]]
if head[Q]=length[Q] then
head[Q] <- 1
else
head[Q] <- head[Q]+1
return x
Could you explain me the "if-else" statements??
Let's start with the queue: $$-\ \ -\ - \underset{\stackrel\uparrow{head}}o \underset{\stackrel\uparrow{end}}-\ -$$
Now we add an element at the end of the queue: $$-\ \ -\ - \underset{\stackrel\uparrow{head}}o\ o \underset{\stackrel\uparrow{end}}-$$ As you can see, we increment end by 1.
When we add another element at the end of the queue, we get: $$\underset{\stackrel\uparrow{end}}-\ \ -\ - \underset{\stackrel\uparrow{head}}o\ o\ \ o$$
In other words, we assign the new element where end was.
If end is at the end of the array, we need to change it to point to the beginning of the array instead of incrementing it.