Our Feeds

Thursday, 24 December 2015

AJITH KP

Queue Implementation using Singly Linked List (SLL) in C++/CPP

Hi GuyZ,
     Queue implementation using Singly Linked List is most efficient because we can add unlimited items to queue unlike using arrays statically. It is another problem you may to solve during your MCA/BTech/BCA graduation years.



Solution

#include <iostream>
using namespace std;
/*
   Queue Implementation using Singly Linked List (SLL)
 Coded By Ajith Kp    (C) http://www.terminalcoders.blogspot.com
*/
struct node
{
 int data;
 node *link = NULL;
};
class Queue{
 node *start, *end;
public:
 Queue(){
  start = end = NULL;
 }
 void menu(){
  int op = 0;
  cout<<"\t\t\tMENU\n1. Enqueue\n2. Dequeue\n3. Show\n4. Exit";
  while(op!=4){
   cout<<"\nOption: ";
   cin>>op;
   switch(op){
    case 1:
     enqueue();
     break;
    case 2:
     dequeue();
     break;
    case 3:
     show();
     break;
    case 4:
     break;
    default:
     cout<<"Error: Try again..";
     break;
   }
  }
 }
 void enqueue(){
  node *nn = new node;
  cout<<"Enter data: ";
  cin>>nn->data;
  if(start==NULL){
   start = nn;
   end = nn;
  }
  else{
   end->link = nn;
   end = nn;
  }
  cout<<"Data "<<nn->data<<" is added to queue...";
 }
 void dequeue(){
  node *nn;
  if(start==NULL){
   cout<<"Error: Queue is empty...";
  }
  else{
   nn=start;
   if(start->link==NULL){
    start=NULL;
    end=NULL;
   }
   else{
    start=start->link;
   }
   cout<<"Data: "<<nn->data<<" is deleted from Queue...";
   delete(nn);
  }
 }
 void show(){
  node *tmp=start;
  cout<<"Queue: ";
  if(tmp){
   while(tmp){
    cout<<tmp->data<<" ";
    tmp=tmp->link;
   }
  }
  else{
   cout<<"Empty...";
  }
 }
};
int main(){
 Queue q;
 q.menu();
 return 0;
}