Implementation of Queue using Link List Functions
void queuesize()
Function to Create an empty queue
create only pointer pointing to NULL
void create()
{
front = rear =
NULL;
}
Function for getting queue size
Take a global variable count and display here.
At every time of enqueue increment count.
and in dequeue function decrement count.
{
printf("\n
Queue size : \'%d\'", count);
}
Function for Enqueing the queue
Add a node with Null pointer at rear side and update rear to new node.
void enq(int data)
{
if (rear == NULL)
{
rear = (struct
node *)malloc(1*sizeof(struct node));
rear->ptr =
NULL;
rear->info
= data;
front = rear;
}
else
{
temp=(struct
node *)malloc(1*sizeof(struct node));
rear->ptr =
temp;
temp->info
= data;
temp->ptr =
NULL;
rear = temp;
}
count++; //count
for counting number of nodes
}
Function for Displaying the queue elements
void display()
{
front1 = front;
if ((front1 ==
NULL) && (rear == NULL))
{
printf("Queue is empty");
return;
}
while (front1 !=
rear)
{
printf("\'%d\' ", front1->info);
front1 =
front1->ptr;
}
if (front1 ==
rear)
printf("\'%d\'", front1->info);
}
Function for Dequeing the queue
Update front pointer to next location and Remove old front element using dummy pointer as front1.
void deq()
{
front1 = front;
if (front1 == NULL)
{
printf("\n Error: Trying to display elements from empty
queue");
return;
}
else
if
(front1->ptr != NULL)
{
front1 =
front1->ptr;
printf("\n Dequed value : %d", front->info);
free(front);
front =
front1;
}
else
{
printf("\n Dequed value : %d", front->info);
free(front);
front =
NULL;
rear =
NULL;
}
count--; //
decrement count of total nodes
}
Function to display front element of queue
int frontelement()
{
if ((front !=
NULL) && (rear != NULL))
return(front->info);
else
return 0;
}
Function for Display if queue is empty or not
If front and rear both are pointing to Null then queue is empty.
void empty()
{
if ((front ==
NULL) && (rear == NULL))
printf("\n Queue empty");
else
printf("Queue not empty");
}
/*
Output
1-Enque
2 - Deque
3 - Front
element
4 - Empty
5 - Display
6 - Queuesize
7 - Exit
Enter choice : 1
Enter data for Enque: 10
Element of Queue
after Enqueque operation:'10'
Enter choice : 1
Enter data for Enque: 20
Element of Queue
after Enqueque operation:'10' '20'
Enter choice : 1
Enter data for Enque:
30
Element of Queue
after Enqueque operation:'10' '20' '30'
Enter choice : 2
Dequed value :
10
Element of Queue
after deque operation:'20' '30'
Enter choice : 3
Front element : 20
Enter choice : 4
Queue not empty
Enter choice : 5
'20' '30'
Enter choice : 6
Queue size : '2'
Enter choice : 7
...Program finished with exit code 0
Press ENTER to exit console.
*/
No comments:
Post a Comment