List for single integer – QUEUE

Posted: February 17, 2012 in Uncategorized

File: queue.h

#ifndef __FS_QUEUE_H__
#define __FS_QUEUE_H__

class Queue;

class Node{
  int _data;
  Node* _next;
  Node(int data, Node* next = (Node*)0);
  friend class Queue;
};

class Queue{
  Node* _head;
public:
  Queue();
  virtual ~Queue();
  int remove();
  void add(int val);
  bool isEmpty();
};

#endif

File: queue.cpp

#include "queue.h"

Node::Node(int data, Node* next){
  _data = data;
  _next = next;
}
Queue::Queue(){
  //Initialize and head point it to NULL 
  _head = (Node*)0;
}
Queue::~Queue(){
  //Method 1
  /*while(Node* p = _head){
    _head = _head->_next;
    delete p;
  }*/

  //Method 2
  while(_head) remove();
}
int Queue::remove(){
  //Initializing a veriable to hold the current
  //data in order to return at the end
  int ret = _head->_data;

  //Copying the current pointer so we can use that
  //to delete after. This is must be done to avoid 
  //memory leak
  Node* toDel = _head;

  //Now head will point to second or next element
  _head = _head->_next;

  //Delete permanently the one removed from list.
  //So it will remove from memory completely
  delete toDel;

  //Return the deleted data
  return ret;
}
void Queue::add(int val){
  //Here we create a Node and that will pointed 
  //by _head. Also using the private copy 
  //constructor to add the given parameter "val"
  //as new data and copy the current _head as 
  //next.
  _head = new Node(val, _head);
}
bool Queue::isEmpty(){
  //Here we are checking where that is pointing
  //to. If it is empty, the head will point to 
  //NULL. So if this is pointing NULL, it will 
  //return true.
  return !_head;
}

File: queuemain.cpp

#include <iostream>
using namespace std;

#include "queue.h"
int main(){
  bool done = false;
  int input;
  int i=-1;
  Queue Q;
  while(!done) {
    cout<<"Enter an integer (0 to terminate and remove):";
    cin>>input;
    if(input) Q.add(input);
    else done=true;
    i++;
  }
  cout<<i<<((i==1)?(" integer Added"):(" integers Added"))<<endl<<endl<<endl;
  cout<<"QUEUE LIST: "<<endl<<endl;
  while(!Q.isEmpty()) cout<<Q.remove()<<" -> ";

  cout<<"NULL"<<endl<<endl;
  return 0;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s