Applications of Linked List (Queue)
Applications Of Linked List
Part 2 Queue
Now that we have an understanding of what linked list are and have seen where the singly linked list can be used , lets check the usage of doubly linked list.
Doubly Linked List:
Doubly Linked List can be used for various applications, one of the application is for modelling finite state machines, each node in doubly linked list can act as a state in finite state machine. Another application is if we want to implement Queue Abstract Data Structure.
Queue:
Queue is an abstract data structure, Queue is also called as FIFO , as it follows First in first out principle. The item/data/process which entered first in the queue data structure is processed first in queue data structure. Queue supports two basic operations , enqueue and dequeue .
Enqueue
- enqueue means to add an element/data/node at the end of the queue.
Dequeue
- dequeue means to process the element/data/node which is at the front of the queue and remove it from the queue
CPP Program for Queue:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// main.cpp | |
// queue | |
// Created by Sarvesh Bhatnagar on 05/03/18. | |
// Copyright © 2018 introtoalgo.com. All rights reserved. | |
// | |
#include <iostream> | |
using namespace std; | |
struct doublyLinkedList{ | |
int id; | |
struct doublyLinkedList *next; | |
struct doublyLinkedList *prev; | |
}; | |
struct doublyLinkedList *temp,*first,*last; | |
void makeDoublyLinkedList(); | |
void enQueue(); | |
void deQueue(); | |
int main() { | |
cout<<"Enter Number of Queue Items you want to insert"<<endl; | |
int n; | |
cin>>n; | |
for (int i = 0; i<n; i++) { | |
enQueue(); | |
} | |
cout<<"Enter how many Queue items you want to process? "<<endl; | |
cin>>n; | |
for (int i = 0; i<n; i++) { | |
deQueue(); | |
} | |
return 0; | |
} | |
void enQueue(){ | |
temp = new doublyLinkedList(); | |
temp->prev = NULL; | |
temp->next = NULL; | |
if (first == NULL) { | |
first = temp; | |
} | |
else{ | |
last->prev = temp; | |
temp->next = last; | |
} | |
last = temp; | |
cout<<"Enter id"<<endl; | |
cin>>temp->id; | |
} | |
void deQueue(){ | |
temp = first; | |
if (first != NULL) { | |
cout<<first->id<<endl; | |
if (first->prev != NULL) { | |
first = first->prev; | |
} | |
else{ | |
cout<<"Queue Emptied"<<endl; | |
first = NULL; | |
} | |
free(temp); | |
} | |
else{ | |
cout<<"Empty Queue"<<endl; | |
} | |
} |