Thursday, December 6, 2007

Queue

The queue implementation will create 2 entries in the associative array to maintain pointers to the start and end of the queue ( 'curr' and 'next'). The 'curr' pointer points to the current element in the queue (the one that will be returned when the 'dequeue' function is called); while the 'next' pointer points to the position where the next 'enqueue' should insert the item to. The following diagrams illustrates the operation performed on the array as 2 elements are added to the queue, and then a function call to 'dequeue' is made at the end. The numbers to the left of the queue is the associative index of the array (by defining 'curr' and 'next', the array becomes an associative array).

Queue empty and initialized:
Statement: queue_init (my_queue);

3
2
1
0 <- curr, next Queue with 1 element enqueued: Statement: enqueue (my_queue, "a"); 3 2 1 <- next 0 a <- curr Queue with 1 more element enqueued: Statement: enqueue (my_queue, "b"); 3 2 <- next 1 b 0 a <- curr Queue after a 'dequeue' function call (the function returns "a"): Statement: dequeue (my_queue, myval); # myval will contain "a" 3 2 <- next 1 b <- curr 0

Queue

queue_init
Initializes a queue. The queue will be cleared of all its existing entries.
queue_length
Returns the length of the queue.
enqueue or queue_push
Adds an entry to the end of the queue.
queue_unpop
Adds an entry to the beginning of the queue. (New in 2.1)
dequeue or queue_pop
Remove an entry from the beginning of the queue.
queue_isempty
Whether the queue is empty.

In programming, a queue is a data structure in which elements are removed in the same order they were entered. This is often referred to as FIFO (first in, first out). In contrast, a stack is a data structure in which elements are removed in the reverse order from which they were entered. This is referred to as LIFO (last in, first out).

No comments: