Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

implementation of queue using linked list in c

#include <stdio.h>
#include <stdlib.h>

// Structure to create a node with data and next pointer
struct node {
	int data;
	struct node *next;
};

struct node *front = NULL;
struct node *rear = NULL;

// Enqueue() operation on a queue
void enqueue(int value) {
	struct node *ptr;
	ptr = (struct node *)malloc(sizeof(struct node));
	ptr->data = value;
	ptr->next = NULL;
	if ((front == NULL) && (rear == NULL)) {
		front = rear = ptr;
	} else {
		rear->next = ptr;
		rear = ptr;
	}
	printf("Node is Inserted

");
}

// Dequeue() operation on a queue
int dequeue() {
	if (front == NULL) {
		printf("
Underflow
");
		return -1;
	} else {
		struct node *temp = front;
		int temp_data = front->data;
		front = front->next;
		free(temp);
		return temp_data;
	}
}

// Display all elements of queue
void display() {
	struct node *temp;
	if ((front == NULL) && (rear == NULL)) {
		printf("
Queue is Empty
");
	} else {
		printf("The queue is 
");
		temp = front;
		while (temp) {
			printf("%d--->", temp->data);
			temp = temp->next;
		}
		printf("NULL

");
	}
}

int main() {
	int choice, value;
	printf("
Implementation of Queue using Linked List
");
	while (choice != 4) {
		printf("1.Enqueue
2.Dequeue
3.Display
4.Exit
");
		printf("
Enter your choice : ");
		scanf("%d", &choice);
		switch (choice) {
		case 1:
			printf("
Enter the value to insert: ");
			scanf("%d", &value);
			enqueue(value);
			break;
		case 2:
			printf("Popped element is :%d
", dequeue());
			break;
		case 3:
			display();
			break;
		case 4:
			exit(0);
			break;
		default:
			printf("
Wrong Choice
");
		}
	}
	return 0;
}
Source by www.scaler.com #
 
PREVIOUS NEXT
Tagged: #implementation #queue #linked #list
ADD COMMENT
Topic
Name
2+4 =