Article 85 - Data Structure - How to Implement Queue in C

This article describes an implementation of the Queue Structure.

For information about the Queue Structure, see Article 31 - Programming Data Structures.

To program a Queue, we need to understand the interface of a Queue.

Interface

  • Enqueue Function
  • Dequeue Function

Implementation

In this implementation, we use the Node structure from the Link List Article, see Article 83 - Data Structure - How to Implement Linked List in C.

Enqueue Function

This function adds an item to the end of the list. That is, the item is the last of all nodes currently in the queue to be removed.

A function to add a node to the queue.

int enqueue( Node ** queue, int content ){
    Node * node;
    
    if( !queue ){
        return -1;
    }

    node = newNode( content );

    if( !node ){
        return -2;
    }

    return addNode( queue, node );
}

Dequeue Function

This function removes the item at the beginning of the list. That is, the item has been in the list the longest (oldest item).

A function to remove a node from the queue.

int dequeue( Node ** queue, int * content ){
    Node * previousNode;
    
    if( !queue || !content ){
        return -1;
    }   

    if( !*queue ){
        return -2;
    }

    for( previousNode = *queue; !previousNode; 
        previousNode = previousNode->next ){
        if( !previousNode->next ){
            break;
        }
    }

    *content = previousNode->content;

    return removeNode( queue, previousNode );
}

Comments (8)

Posted by anonymous - social bookmarks at Thursday, March 14, 2013 8:01 PM

RVrWtB Im grateful for the blog post.Thanks Again. Awesome.

Posted by anonymous - buy cipro at Friday, March 15, 2013 10:48 AM

Major thanks for the blog.Really looking forward to read more. Keep writing.

Posted by anonymous - buy generic viagra at Friday, March 15, 2013 12:27 PM

A round of applause for your blog post.Much thanks again. Keep writing.

Posted by anonymous - cialis online at Friday, March 15, 2013 2:06 PM

Thanks a lot for the blog post.Really looking forward to read more. Cool.

Posted by anonymous - Buy Levitra online at Friday, March 15, 2013 3:46 PM

I am so grateful for your article.Really thank you! Cool.

Post a comment

  • Name:
  • Post:
  • Challenge:

Register or login to post comments easier.


Vantasy World Copyright 2011 - 2017. Vantasy World is a project developed by Vantasy Online. Privacy Policy.