Archive for the ‘Uncategorized’ Category

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;
  virtual ~Queue();
  int remove();
  void add(int val);
  bool isEmpty();


File: queue.cpp

#include "queue.h"

Node::Node(int data, Node* next){
  _data = data;
  _next = next;
  //Initialize and head point it to NULL 
  _head = (Node*)0;
  //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 
  _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):";
    if(input) Q.add(input);
    else done=true;
  cout<<i<<((i==1)?(" integer Added"):(" integers Added"))<<endl<<endl<<endl;
  cout<<"QUEUE LIST: "<<endl<<endl;
  while(!Q.isEmpty()) cout<<Q.remove()<<" -> ";

  return 0;


Posted: January 15, 2012 in Uncategorized

Hello there! Since I have problem in posting cpp programming codes in blogspot, so I moved to wordpress!!