TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
queue_using_linkedlist.cpp
1/*
2 Write a program to implement Queue using linkedlist.
3*/
4#include <iostream>
5
6struct linkedlist {
7 int data;
8 linkedlist *next;
9};
11 public:
12 linkedlist *front;
13 linkedlist *rear;
14
15 stack_linkedList() { front = rear = NULL; }
16 void enqueue(int);
17 int dequeue();
18 void display();
19};
20void stack_linkedList::enqueue(int ele) {
21 linkedlist *temp = new linkedlist();
22 temp->data = ele;
23 temp->next = NULL;
24
25 if (front == NULL)
26 front = rear = temp;
27 else {
28 rear->next = temp;
29 rear = temp;
30 }
31}
32int stack_linkedList::dequeue() {
33 linkedlist *temp;
34 int ele;
35 if (front == NULL)
36 std::cout << "\nStack is empty";
37 else {
38 temp = front;
39 ele = temp->data;
40 if (front == rear) // if length of queue is 1;
41 rear = rear->next;
42 front = front->next;
43 delete (temp);
44 }
45 return ele;
46}
47void stack_linkedList::display() {
48 if (front == NULL)
49 std::cout << "\nStack is empty";
50
51 else {
52 linkedlist *temp;
53 temp = front;
54 while (temp != NULL) {
55 std::cout << temp->data << " ";
56 temp = temp->next;
57 }
58 }
59}
60
61int main() {
62 int op, data;
64 std::cout << "\n1. enqueue(Insertion) ";
65 std::cout << "\n2. dequeue(Deletion)";
66 std::cout << "\n3. Display";
67 std::cout << "\n4. Exit";
68
69 while (1) {
70 std::cout << "\nEnter your choice ";
71 std::cin >> op;
72 if (op == 1) {
73 std::cout << "Enter data ";
74 std::cin >> data;
75 ob.enqueue(data);
76 } else if (op == 2)
77 data = ob.dequeue();
78 else if (op == 3)
79 ob.display();
80 else if (op == 4)
81 exit(0);
82 else
83 std::cout << "\nWrong choice ";
84 }
85 return 0;
86}
int main()
Main function.
int data[MAX]
test data