Tuesday, February 28, 2012

Data Structure and Algorithm - Queue - queueAsLinkedlist.h source code

queueAsLinkedlist.h as template


#include <iostream>
#include <string.h>
#include <assert.h>
using namespace std;

// Class Node
template <class Type>
class Node{
public:
    Type node;
    Node* next;
    Node(Type node){
        this->node = node;
        next = NULL;
    }
};

// Class QueueType
template <class Type>
class queueType{
private:
    int count;
    Node<Type> *first;
    Node<Type> *last;
    Node<Type> *newNode;
public:
    queueType(){
        first = NULL;
        last = NULL;
        count = 0;
    }
    void addQueue(Type newItem){
        newNode = new Node<Type>(newItem);          // create new Node
        if(count == 0){                             // if queue is empty
            first = newNode;
            last = newNode;
        }else{                                      // if queue is not empty
            last->next = newNode;
            last = newNode;
        }
        count++;
    }
    void deleteQueue(){
        if(count == 0){                             // if queue is empty
            cout<<"Queue is empty, can't delete...."<<endl;
        }else{
            if(count > 1){
                Node<Type> *delNode;
                delNode = first;
                first = first->next;
                delete delNode;
                count--;
            }else{                      // if queue contents only one item
                first = NULL;
                last = NULL;
                delete newNode;
                count--;
            }
        }
    }
    int getCount(){
        return count;
    }
    Type front(){                               // return front value of queue
        if(count > 0){      
            return first->node;
        }else{
            return '\0';
        }
    }
    Type back(){                                // return back value of queue
        if(count > 0){      
            return last->node;
        }else{
            return '\0';
        }   
    }
    ~queueType(){
        for(int i =0 ; i<count ; i++){
            Node<Type> *delNode;
            delNode = first;
            first = delNode->next;
            delete delNode;
        }
    }
   
};

No comments:

Post a Comment