display | more...

Rather generic C++ code for a queue data structure. Data are ints to make it simple. I give no guarantees of it working, but it works fine for me :P

/*
  queue.h
  header file for queue.cpp, implements a queue data structure using a linked list.
*/


#ifndef QUEUE_H
#define QUEUE_H

#include 

class queue;

class node
{
  friend queue;
 private:
  int data;
  node *link;
  //node *backward;
};

class queue
{
 public:
  queue();
  ~queue();
  bool isEmpty();
  int size();
  void push(int p);
  int peek();
  int pop();
 private:
  node *front;
  node *rear;
  bool empty;
  int howBig;
};

#endif //QUEUE_H

/*
  queue.cpp
  source code for a queue data structure, implemented using a linked list
*/


#include 
#include "queue.h"

queue::queue()
{
  front = rear = 0;
  //empty = true;
  howBig = 0;
}

queue::~queue()
{
  node *next;
  while(front != 0)
    {
      next = front->link;
      delete front;
      front = next;
    }
}




int queue::size()
{
  return howBig;
}

bool queue::isEmpty()
{
  if(front)
    empty = false;
  else
    empty = true;
  return(empty);
}

int queue::peek()
{
  if(isEmpty())
    {
      cerr < "queue is empty\n";
      exit(1);
    }
  return front->data;
}

void queue::push(int p)
{
  node *temp = new node;
  
  temp->data = p;
  temp->link = 0;
  howBig++;
  empty = false;
  if(front)
    {
      rear->link = temp;
    }
  else
    {
      front = temp;
    }
  rear = temp;
  return;

}

int queue::pop()
{
  if(isEmpty()) exit(1);
  int x = front->data;
  node *temp = front;
  front = front->link;
  delete temp;
  howBig--;
  return x;
}