ProAnswers.org

Algorithm Add an element to the queue

algorithm Add an element to the queue

Array representation

typedef struct queue{
    int QArray[MAX_SIZE+1];//can accommodate MAX_SIZE number of elements
    int front, rear;
}queue;


[b]Linked list representation[/b]

    
typedef struct QNode{
    int data;
    struct QNode *next;
}QNode;
typedef struct queue{
    QNode *front, *rear;
}queue;



[b]Checking if a queue is empty[/b]


    
int isEmpty(queue *q){
    if(q -> front == q -> rear) //Queue is Empty
        return 1;
    else
        return 0;
}


[b]Adding an element in a queue

For array representation[/b]


    
void enqueue(queue *q, int x){
    if(q -> rear == MAX_SIZE)
        return;
    else{
        q -> rear = q -> rear + 1;
        q -> QArray[q -> rear] = x;
    }
}

[b]For linked list representation[/b]

    
void enqueue(queue *q, int x){
    QNode *qnode;
    qnode = (QNode *)malloc(sizeof(QNode));
    qnode -> data = x;
    qnode -> next = NULL;
    if(q -> front == NULL){
        q -> rear = q -> front = qnode;
        return;
    }
    q -> rear -> next = qnode;
    q -> rear = qnode;
}