Friday, March 02, 2012

Queues

Queues

A queue is a variable-size, ordered collection of homogeneous elements. A queue supports constant time access to all its elements as well as constant time insertion and removal at the beginning or the end of the queue.

Each element in a queue is identified by an ordinal number that represents its position within the queue, with 0 representing the first, and $ representing the last. A queue is analogous to a one-dimensional unpacked array that grows and shrinks automatically.

Thus, like arrays, queues can be manipulated using the indexing, concatenation, slicing operator syntax, and equality operators.

byte q1[$]; // A queue of bytes
string names[$] = { "Bob" }; // A queue of strings with one element
integer Q[$] = { 3, 2, 7 }; // An initialized queue of integers
bit q2[$:255]; // A queue whose maximum size is 256 bits
//The empty array literal {} is used to denote an empty queue.

Queue Operators

Queues support the same operations that can be performed on unpacked arrays, and using the same operators and rules except as defined below:

int q[$] = { 2, 4, 8 };
int p[$];
int e, pos;
e = q[0]; // read the first (left-most) item
e = q[$]; // read the last (right-most) item

Queue Methods

In addition to the array operators, queues provide several built-in methods

The prototype for the size() method is:

function int size();

The size() method returns the number of items in the queue. If the queue is empty, it returns 0.

for ( int j = 0; j < q.size; j++ )
$display( q[j] );

insert()

The prototype of the insert() method is:

function void insert(int index, queue_type item);

delete()

The prototype of the delete() method is:

function void delete(int index);

pop_front()

The prototype of the pop_front() method is:

function queue_type pop_front();

pop_back()

The prototype of the pop_back() method is:

function queue_type pop_back();

The pop_back() method removes and returns the last element of the queue.

push_front()

The prototype of the push_front() method is:

function void push_front(queue_type item);

The push_front() method inserts the given element at the front of the queue.

push_back()

The prototype of the push_back() method is:

function void push_back(queue_type item);

No comments:

Post a Comment

Popular Posts