C++: Queue implementation using Linked List (Data Structure)

We have already learnt about Queue int the post C++: Implementation of Queue using Array (Data Structure). Now we are implementing Queue using Linked List which we have learnt in C++: Singly Linked List using Template (Data Structure).

Here is the C++ program for implementing Queue using Linked List.

#include <iostream>
template<class T>class Queue{  struct Node{    T data;    Node* next;    Node(T val):data(val),next(nullptr) {}  };  Node *front, *rear;
  public:      Queue():front(nullptr),rear(nullptr){}     ~Queue();      void enqueue(T val);      T dequeue();      Queue(Queue const&)              =delete;      Queue& operator =(Queue const&)  =delete;
      template <class U>      friend std::ostream & operator<<(std::ostream & os, const Queue<U> & q){      q.display(os);      return os;      }
  private:      void display(std::ostream& out = std::cout) const{      for(Node* loop = front; loop != nullptr; loop = loop->next){            out << loop->data << " ";      }    }};
template<class T>void Queue<T>::enqueue(T val){Node* node=new Node(val);node->next=nullptr;  if(front==nullptr){    front=rear=node;    rear->next=nullptr;  }  else{    rear->next=node;    rear=node;    rear->next=nullptr;  }}
template<class T>T Queue<T>::dequeue(){  if(front==nullptr)  std::cout<<"Empty Queue"<<std::endl;
  else{    Node* node=front;    front=front->next;    T tmp=std::move(node->data);    delete node;    return tmp;    }}
template<class T>Queue<T>::~Queue(){  for(Node* next;front!=nullptr;front=next){    next=front->next;    delete front;  }}
int main(){    Queue<int> q1;    q1.enqueue(5);    q1.enqueue(8);    q1.enqueue(1);    q1.enqueue(30);    std::cout<<q1<<std::endl;    std::cout<<q1.dequeue()<<std::endl;    std::cout<<q1<<std::endl;
    return 0;}

Remember to use delete to delete a node to avoid memory leak.

 Follow us on

You may also like:

C++: Stack implementation using LinkedList (Data Structure)
C++: Doubly Linked List using Template (Data Structure)
What is "namespace" and why do we use it?
C++: Understanding Template
C++: Implementation of Stack using Array (Data Structure)


Popular Posts

Top 10 Web Sites Every Programmer Should Visit Daily

How do I improve my logical thinking and problem solving skills?

C++: STL Iterators