mercredi 29 janvier 2020

Queue Implementation Template return type function in C++

I am trying to implement Queue Data Structure using Linked List in C++, where I've made use of classes in both the Linked List and Queue. One thing which I am not getting is that for example, I've written a method front() which will return the top element or the first element of the queue. However, I'm confused about what should I return and how should I return in the case of templated class when my queue is empty. If it would've been int type queue, I would've simply returned -1. Here I'm confused what should I return if my queue() is already empty and how should I return from a templated class.

Here's the code I've written

// Implementation of Queue Data Structure using List
#include<iostream>
using namespace std;

template<typename T>
class Node
{
public:
    T data;
    Node<T>*next;
};
template<typename S>
class Queue
{
public:
    Node<S>*q = NULL;
    void enqueue(S data){
        Node<S>* newNode = new Node<S>;
        newNode->data = data;
        newNode->next = NULL;
        if(q!=NULL){
            Node<S>* temp = q;
            while(temp->next!=NULL){    
                temp = temp->next;
            }
            temp->next = newNode;
        }
        else{
            q = newNode;
        }
    }
    void print(){ //Utility method for printing the queue with ease
        Node<S>*temp = q;
        while(temp){
            cout<<temp->data<<endl;
            temp = temp->next;
        }
    }
    auto dequeue() -> decltype(q->data){
        Node<S>*temp = q;
        q = q->next;
        S value = temp->data;
        delete temp;
        return value;
    }
    auto front() -> decltype(q->data){
        return q->data;
    }
};
int main()
{
    Queue<int>q;
    q.enqueue(1);
    q.enqueue(2);
    q.enqueue(3);

    cout<<"Front is "<<q.front()<<endl;

    cout<<"Before dequeue() printing\n";

    q.print(); 

    cout<<"Dequeue operation() "<<q.dequeue()<<endl;

    cout<<"After deueue() printing\n";

    q.print();

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire