jeudi 27 mai 2010

Implement stack using a queue

General idea: in order to pop an element, we need to extract all the elements and insert them at the beginning of the queue execpt for the last one that needs to be returned. push is easy, simply add to the top if the queue is not filled up.

Here is the pseudo-code for the push function:

K = queue actual size of the queue
N = max queue size
for i = K ; i < N ; i++
q.top(None)
for i = 0 ; i < K - 1 ; i++
q.bottom (q.bottom())
return q.bottom()

Aucun commentaire:

Enregistrer un commentaire