Tuesday, 9 April 2013

Queue add method

To do:
 - Do the add method of the Queue as exercise

Source Code:
Queue.h file
#pragma once
#ifndef __QUEUE_H__
#define __QUEUE_H__

class Queue;
class Node{
 int _data;
 Node* _next;
 Node(int data, Node* next= (Node*)0);
 friend class Queue;
};
class Queue{
private:
 Node* _head;
public:
 Queue();
 void add(int data);
 int remove();
 bool isEmpty();
 virtual ~Queue();
};
#endif


Queue.cpp file
#include "queue.h"  

Node::Node(int data, Node* next) {
 _data = data;
 _next = next;
}
Queue::Queue() {
 _head = (Node*)0;
}
void Queue::add(int data) {
 // 1 create node, and 2 point to next node
 Node* toAdd= new Node(data, _head);
 _head = toAdd; // 3 point to new node
}
int Queue::remove() {
 int ret = _head->_data;  // 1
 // int ret = (*_head)._data;  // 1 crazy but ok
 Node* toDel = _head;  // 2
 _head = _head->_next;  // 3 
 //  _head = toDel->_next; //  same as 3
 delete toDel; // 5
 return ret;
}
bool Queue::isEmpty() {
 /*if(_head == (Node*)0) {
  return true;
 }
 else {
  return false;
 }*/
 return _head == (Node*)0 ? true : false;
}
Queue::~Queue() {
 while(!isEmpty()) {
  remove();
 }
}

No comments:

Post a comment