Anda di halaman 1dari 10

Circular Queue

Joy Mukherjee
Programming & Data Structures
Circular Queue using Linked List

typedef struct node


{
int data;
struct node *next;
}node;

typedef struct queue{


node *tail;
}queue;
Circular Queue using Linked List

The keyword struct is used to create an user-defined


datatype
Here struct node is an user-defined datatype
It has two members: data of type int & next of type
struct node *.
The keyword typedef tells the compiler that struct node
(written before {) and node (written after }) have
identical properties .
Circular Queue has one member: tail of type node *( or
struct node *).
Circular Queue

12 2000 2 3000 99 1000

1000 2000 Q->tail=3000


queue * enqueue(queue *Q, int data)

node *new_node = NULL;

new_node = (node *)malloc(sizeof(node));

new_node->data = data;

// Set it point to itself


new_node->next = new_node;
queue * enqueue(queue *Q, int data)
if(isEmpty(Q)) {
Q->tail = new_node; return Q;
}

// Set the next of new_node to the next of current Q->tail


new_node->next = Q->tail->next;

// Set the next of current Q->tail to new_node


Q->tail->next = new_node;

// Set Q->tail to new_node


Q->tail = new_node;
return Q;
Q = enqueue(Q, 33)
node *new_node = (node *)malloc(sizeof(node));
new_node->data = data;
new_node->next = new_node;

12 2000 2 3000 99 1000 33 500

1000 2000 Q->tail=3000 new_node=500

new_node->next = Q->tail->next;
Q->tail->next = new_node;
Q->tail = new_node;
return Q;

12 2000 2 3000 99 500


1000 33 1000

1000 2000 Q->tail=3000


3000 new_node=500
Q->tail=500
queue * dequeue(queue *Q)
if (isEmpty(Q)) {
printf("queue is Empty.\n"); return Q;
}
node *temp = Q->tail;

// If there is single node in the Circular Queue


if(temp->next == Q->tail) {
free(temp);
Q->tail = NULL;
return Q;
}
Cont.

node *head = Q->tail->next;

// Set next of Q->tail to point to the next of head


Q->tail->next = head->next;

free(head);

return Q;
Q = dequeue(Q)
node *head = Q->tail->next;

12 2000 2 3000 99 1000

head=1000 2000 Q->tail=3000

Q->tail->next = head->next;

12 2000 2 3000 99 2000

head=1000 2000 Q->tail=3000

free(head); 2 3000 99 2000


return Q;
2000 Q->tail=3000

Anda mungkin juga menyukai