Free Web Hosting Provider - Web Hosting - E-commerce - High Speed Internet - Free Web Page
Search the Web

Queue->Linked List implementation->Insert operation

As a dynamic list will implement the Queue, we won't check the 'queue overflow' condition here. Here, we have two pointers -- front and rear, pointing to beginning and end of the Queue. When 'front' and 'rear' both point to NULL, Queue is empty. Every time we add an element to the queue, the 'rear' pointer shifts forward to point to that newly added element. Check out the algo...

Algorithm:-
Step-1: Create the new node
Step-2: If the Queue is empty go to step-3; or else go to step-4
Step-3: Make the 'front', 'rear' and 'queue' pointers to point to it. Quit.
Step-4: Add it to the end of the queue. Shift 'rear' pointer to point to this newly added element. Quit. 

C implementation:-
struct node
{
 int value;
 struct node *next;
}
struct node *queue, *front, *rear;

main( )
{
 queue = front = rear = NULL; /*queue is initially empty*/
..
..
 insert(new_value);
..
 insert(new_value);
..
}

insert(int value)
{
 struct node *new;

 new = (struct node *)malloc(sizeof(node));
 new->value = value;
 new->next = NULL;

 if(front == NULL) 
   {
    queue = new;
    front = rear = queue;
   }
 else
   {
    rear->next = new;
    rear = new;
   }
}

Related Operations:
Queues - Concepts
Array implementation - add( ) and delete( )
Linked List implementation - add( ) and delete( )
Circular queues - add( ) and delete( )

Index || Doubts / Clarifications || Related Topics || Web Links