Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- using namespace std;
- struct node{
- int data;
- node *next;
- };
- class queue{
- node *front;
- node *rear;
- public:
- queue(){
- front = rear = NULL;
- }
- bool isEmpty(){
- if(rear == NULL){
- return true;
- }
- else{
- return false;
- }
- }
- void enqueue(int v){
- node *t = new node;
- t -> data = v;
- t -> next = NULL;
- //If queue is empty, new node is front and rear both
- if(rear == NULL){
- front = t;
- rear = t;
- return;
- }
- //Add new node at end of the queue
- rear -> next = t;
- rear = t;
- }
- int dequeue(){
- if(front == NULL){
- //cout << "Queue is empty" << endl;
- return -1;
- }
- //Store previous front and move front one node ahead
- node *t = front;
- front = front -> next;
- //If front becomes NULL, change rear as NULL too
- if(front == NULL){
- rear == NULL;
- }
- int val = t -> data;
- free(t);
- return val;
- }
- void display(){
- node *t=front;
- while(t!=NULL){
- cout << t->data <<" -> ";
- t=t->next;
- }
- cout<<"NULL\n";
- }
- };
- int main(){
- queue q;
- int ch = 10;
- while(ch != 0){
- cout << "Enter your choice" << endl;
- cout << "1: Enqueue element" << endl;
- cout << "2: Dequeue element" << endl;
- cout << "0: Exit" << endl;
- cin >> ch;
- switch(ch){
- case 1:
- int value;
- cout << "Enter value: " << endl;
- cin >> value;
- q.enqueue(value);
- q.display();
- break;
- case 2:
- cout << "The dequeued element is: " << q.dequeue() << endl;
- q.display();
- break;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement