Represent the queue as two lists. The first list holds elements in
the front of the queue, and the second elements in the back of the queue (in reverse order). Insert can now be implemented simply by consing the new element to the back of the queue. If the front is non-empty, remove simple returns the first element of the front, otherwise the elements from the back are moved to the front. This gives insert and remove amortized time O(1).
(modulequeuemzscheme
(provideemptyempty?insertremovefirst)
(define-structqueue (frontback) (make-inspector))
(defineempty (make-queue'() '()))
; empty? : queue -> boolean
; is the queue Q empty?
(define (empty?Q)
(and (null? (queue-frontQ))
(null? (queue-backQ))))
; insert : queue elm -> queue
; return a new queue holding both the elements
; from the old queue Q and the new element x
(define (insertQx)
(make-queue (queue-frontQ)
(consx (queue-backQ))))
; remove : queue -> (values queue elm)
; return two values, the first a queue with the same elements
; as the queue Q except for the element in front of the queue
; the second a value is the front element of Q
(define (removeQ)
(cond
[(and (null? (queue-frontQ)) (null? (queue-backQ)))
(error"remove: The queue is empty")]
[(null? (queue-frontQ))
(remove (make-queue (reverse (queue-backQ)) '()))]
[else
(values (car (queue-frontQ))
(make-queue (cdr (queue-frontQ)) (queue-backQ)))]))
; first : queue -> element
; return the first element in the non-empty queue Q
(define (firstQ)
(cond
[(empty?Q)
(error"first: The queue is empty")]
[(null? (queue-frontQ))
(first (make-queue (reverse (queue-backQ)) '()))]
[else
(car (queue-frontQ))]))
)
One advantage of a functional datastructures is that they can be used by multithreaded programs (such as web servlets) without problems.
-- JensAxelSoegaard - 17 Apr 2004