//----------------------------------------------------------------------
//  IMPLEMENTATION FILE (plist.cpp)
//  This module exports List, an ADT for maintaining lists of
//  process objects.
//----------------------------------------------------------------------
#include "bool.h"
#include "plist.h"


PList::PList()
{
 head = new NodeType1;
 head -> link = NULL;
 head -> process = NULL;
}

Boolean PList::IsEmpty() const
{
 return( head -> link == NULL );
}

void PList::Insert( Process *newproc )
{
 NodePtr1 prev, next;
 Boolean GreaterEqual = FALSE;

 NodePtr1 NewPtr = new NodeType1;
 NewPtr -> process = newproc;

 // First we find the previous node
 prev = head;
 while ( (prev -> link != NULL) && ( !GreaterEqual ) )
  {
   next = prev -> link;
   if ( newproc->getpid() >= next->process->getpid() )
    GreaterEqual = TRUE;
   else
    prev = next;
  }            // end of while to find prev

 // If GreaterEqual is TRUE, then prev -> link is not NULL and
 // the next key is >= the new key.
 // Else we have come to the end of the list and prev -> link is NULL.
 if ( prev -> link == NULL )
  {
   NewPtr -> link = NULL;
   prev -> link = NewPtr;
  }
 else 
  {
   NewPtr -> link = next;
   prev -> link = NewPtr;
  }
}                       // end of insert function

Process  *PList::Remove( int pid )
{
 NodePtr1 prev, next, temp;
 Boolean KeyFound = FALSE;
 Boolean GreaterEqual = FALSE;
 Process *PPtr = NULL;


 // First we find the previous node
 prev = head;
 while ( (prev -> link != NULL) && ( !GreaterEqual ) )
  {
   next = prev -> link;
   if ( pid >= next->process->getpid() )
    GreaterEqual = TRUE;
   else
    prev = next;
  }            // end of while to find prev
 
 if ( GreaterEqual && pid == next->process->getpid() )
  {
   KeyFound = TRUE;
   temp = next;
   prev -> link = next -> link;
   PPtr = temp->process;
   delete temp;
  }
 return PPtr;
}

void PList::Display() const
{
 NodePtr1 temp = head -> link;
 while ( temp != NULL )
 {
	temp->process->Display();
	temp = temp->link;
 }
}

PList::~PList()
{
 NodePtr1 p, next;

 p = head;
 head = NULL;
 while ( p!= NULL )
 {
   next = p -> link;
   delete p;
   p = next;
 }
}   


