Hot Topics

Data Structure
Algorithm:
Prepare the structure of a doubly linked list with its data member
Take two pointers front and rear and initiate them with NULL
push():To push a node in queue create a new node and if the queue is empty then insert the node and assign both front and rear pointer on it.If the queue is not empty then link the newly created node with the last node of linked list
pop():To remove element queue must not be empty.Attach a pointer to the front of queue and reassign the front pointer of queue to the next node.
display():Attach a pointer to the front node of queue and using it keep printing and traversing the queue.
getFront():Get the data from the node pointed by the front pointer
getRear():Get the data from the node pointed by the rear pointer
#include
using namespace std;
// Creation of doubly linked list
struct Node
{
int data;
Node *prev;
Node *next;
Node(int d)
{
data = d;
next = NULL;
prev = NULL;
}
};
// structure of queue
class Queue
{
public:
Node *front, *rear;
Queue() { front = rear = NULL; }
bool isEmpty()
{
if (front == NULL && rear == NULL)
return true;
else
return false;
}
/*function to insert element from rear*/
void push(int d)
{
Node *temp = new Node(d);
// if queue don't have space
if (temp == NULL)
cout << "Overflow" <prev = rear;
rear->next = temp;
rear = temp;
}
}
cout <data << " is inserted in queue" << endl;
}
/*remove element from front*/
void pop()
{
/*queue is empty nothing can be deleted*/
if (isEmpty())
{
cout << "Queue is empty" <next;
/*only one element is present in queue*/
if (front == NULL)
{
rear = NULL;
}
else
{
front->prev = NULL;
}
cout <data << " is deleted from queue" << endl;
delete temp;
}
}
/*function to display elements available in queue*/
void display()
{
/*attaching a pointer to front of queue*/
Node *temp = front;
if (front == NULL)
{
cout << "Queue is empty" << endl;
}
else
{
/*traversing the nodes in queue using that pointer and stop when it reaches NULL*/
while (temp != NULL)
{
cout <data <next;
}
cout << endl;
}
}
/*function to get the front element*/
void getFront()
{
if (isEmpty())
cout << "Queue is empty" << endl;
cout << "The element at front is " <data << endl;
}
/*function to get the rear element*/
void getRear()
{
if (isEmpty())
cout << "Queue is empty" << endl;
cout << "The element at rear is " <data << endl;
}
};
int main()
{
Queue q1;
q1.pop();
q1.push(5);
q1.push(6);
q1.push(10);
q1.push(13);
q1.push(15);
q1.display();
q1.pop();
q1.display();
q1.getFront();
q1.getRear();
return 0;
}
Output
Queue is empty
5 is inserted in queue
6 is inserted in queue
10 is inserted in queue
13 is inserted in queue
15 is inserted in queue
5 6 10 13 15
5 is deleted from queue
6 10 13 15
The element at front is 6
The element at rear is 15