implement queue using linked list in c

C program for implement queue using linked list. Here more information.

// Include header file
#include <stdio.h>
#include <stdlib.h>
/*
  C Program for
  Implement queue using linked list
*/
// Create Q node
typedef struct QNode
{
	// Define useful field of QNode
	int data;
	struct QNode * next;
}QNode;

QNode * getQNode(int value)
{
	// Create dynamic memory of QNode
	QNode * me = (QNode * ) malloc(sizeof(QNode));
	if (me == NULL)
	{
		// Failed to create memory 
		return NULL;
	}
	me->data = value;
	me->next = NULL;
	return me;
}
typedef struct MyQueue
{
	// Define useful field of MyQueue
	struct QNode * head;
	struct QNode * tail;
	int count;
}MyQueue;

MyQueue * getMyQueue()
{
	// Create dynamic memory of MyQueue
	MyQueue * me = (MyQueue * ) malloc(sizeof(MyQueue));
	if (me == NULL)
	{
		// Failed to create memory 
		return NULL;
	}
	me->head = NULL;
	me->tail = NULL;
	me->count = 0;
	return me;
}
int size(MyQueue * me)
{
	return me->count;
}
int isEmpty(MyQueue * me)
{
	return me->count == 0;
}
// Add new node of queue
void enqueue(MyQueue * me, int value)
{
	// Create a new node
	QNode * node = getQNode(value);
	if ((me->head == NULL))
	{
		// Add first element into queue
		me->head = node;
	}
	else
	{
		// Add node at the end using tail 
		me->tail->next = node;
	}
	me->count++;
	me->tail = node;
}
// Delete a element into queue
int dequeue(MyQueue * me)
{
	if ((me->head == NULL))
	{
		printf("Empty Queue");
		return -1;
	}
	// Pointer variable which are storing 
	// the address of deleted node
	QNode * temp = me->head;
	// Visit next node 
	me->head = me->head->next;
	me->count--;
	if ((me->head == NULL))
	{
		// When deleting a last node of linked list
		me->tail = NULL;
	}
  	int v = temp->data;
  	free(temp);
	return v;
}
// Get front node
int peek(MyQueue * me)
{
	if ((me->head == NULL))
	{
		printf("Empty Queue");
		return -1;
	}
	return me->head->data;
}
int main()
{
	MyQueue * task = getMyQueue();
	// Initially number of element
	printf("isEmpty :  %d\n", isEmpty(task));
	// Add element into queue
	enqueue(task, 10);
	enqueue(task, 20);
	enqueue(task, 30);
	enqueue(task, 40);
	enqueue(task, 50);
	// Test other function
	printf("size : %d\n", size(task));
	printf("peek :  %d\n", peek(task));
	printf("dequeue :  %d\n", dequeue(task));
	printf("size :  %d\n", size(task));
	printf("peek :  %d\n", peek(task));
	printf("isEmpty :  %d\n", isEmpty(task));
}

Output

isEmpty :  1
size : 5
peek :  10
dequeue :  10
size :  4
peek :  20
isEmpty :  0


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved