TheAlgorithms-C-Plus-Plus/data_structure/queue_using_linkedlist.cpp

100 lines
1.9 KiB
C++
Raw Normal View History

2020-03-08 15:57:51 +08:00
/*
Write a program to implement Queue using linkedlist.
*/
#include <iostream>
2020-03-08 15:57:51 +08:00
struct linkedlist
{
int data;
linkedlist *next;
2020-03-08 15:57:51 +08:00
};
class stack_linkedList
{
public:
2020-03-08 15:57:51 +08:00
linkedlist *front;
linkedlist *rear;
stack_linkedList() { front = rear = NULL; }
2020-03-08 15:57:51 +08:00
void enqueue(int);
int dequeue();
void display();
};
void stack_linkedList::enqueue(int ele)
{
linkedlist *temp = new linkedlist();
temp->data = ele;
temp->next = NULL;
2020-03-08 15:57:51 +08:00
if (front == NULL)
front = rear = temp;
else
{
rear->next = temp;
rear = temp;
2020-03-08 15:57:51 +08:00
}
}
int stack_linkedList::dequeue()
{
2020-03-08 15:57:51 +08:00
linkedlist *temp;
int ele;
if (front == NULL)
std::cout << "\nStack is empty";
else
{
temp = front;
ele = temp->data;
if (front == rear) // if length of queue is 1;
rear = rear->next;
front = front->next;
delete (temp);
2020-03-08 15:57:51 +08:00
}
return ele;
}
void stack_linkedList::display()
{
if (front == NULL)
std::cout << "\nStack is empty";
else
{
2020-03-08 15:57:51 +08:00
linkedlist *temp;
temp = front;
while (temp != NULL)
{
std::cout << temp->data << " ";
temp = temp->next;
2020-03-08 15:57:51 +08:00
}
}
}
int main()
{
int op, data;
2020-03-08 15:57:51 +08:00
stack_linkedList ob;
std::cout << "\n1. enqueue(Insertion) ";
std::cout << "\n2. dequeue(Deletion)";
std::cout << "\n3. Display";
std::cout << "\n4. Exit";
while (1)
{
std::cout << "\nEnter your choice ";
std::cin >> op;
if (op == 1)
2020-03-08 15:57:51 +08:00
{
std::cout << "Enter data ";
std::cin >> data;
2020-03-08 15:57:51 +08:00
ob.enqueue(data);
}
else if (op == 2)
data = ob.dequeue();
else if (op == 3)
2020-03-08 15:57:51 +08:00
ob.display();
else if (op == 4)
2020-03-08 15:57:51 +08:00
exit(0);
else
std::cout << "\nWrong choice ";
2020-03-08 15:57:51 +08:00
}
2020-04-21 23:55:55 +08:00
return 0;
2020-03-08 15:57:51 +08:00
}