
#include <iostream>
#include "queue.h"

Queue::Queue () 
{
  Front = Rear = NULL;
}

Queue::~Queue () 
{ 
  while (Front != NULL)
    {
      Rear = Front->next;
      delete Front;
      Front = Rear;
    }
}

bool 
Queue::Enqueue (char c)
{
  Node *ptr;

  ptr = new Node;
  if (ptr == NULL)
    return false;
  ptr->c = c; ptr->next = NULL;
  if (Rear != NULL)
    {
      Rear->next = ptr;
     }
  else
    {
      Front = ptr;
    }
  Rear = ptr;
  return true;
}

bool 
Queue::Dequeue (char& c)
{
  Node *ptr = Front;

  if (Front != NULL)
    {
      Front = Front->next;
      c = ptr->c;
      delete ptr;
    }
  if (Front == NULL)
    Rear = NULL;
  return true;
}

bool 
Queue::isEmpty ()
{
  return Front ? false : true;
}


bool
Queue::Print () {
  Node *Prev = Front;
 
  while (Prev) {
      cout << Prev->c << " ";
      Prev = Prev->next;
    }
  cout << endl;
}

bool 
Queue::Reverse () {
  Node *Prev1, *Prev2;
 
  Rear = Front;
  if (Front == NULL) return true;      // List is empty
  Prev2 = Front; Prev1 = Front->next;  // Set initial value for Prev2
  if (Prev1 == NULL) {
    return true;                       // List has only one element
   }
  Front = Prev1->next;  // Set initial value for Prev1
  Prev2->next = NULL;                  // Set the new end of the list
  while (Front != NULL) {              // while the end is not reached
      Prev1->next = Prev2;               // Change the pointer direction
      Prev2 = Prev1; Prev1 = Front;      // Advance
      Front = Front->next;               // Advance (2)
    }
  Prev1->next = Prev2;                 // The last set
  Front = Prev1;                       // Set the new Front of the list
  return true;
}


