ex-col-04-training/waiting_room/WaitingRoom/PatientQueue.cs
2025-01-13 20:30:20 +01:00

96 lines
No EOL
2.4 KiB
C#

namespace WaitingRoom;
/// <summary>
/// A queue implementation which can be used to represents the waiting queue of
/// patients at a doctor's office.
/// </summary>
public sealed class PatientQueue
{
private Node? _head;
/// <summary>
/// Gets the number of patients currently waiting in this queue
/// </summary>
public int Size { get; private set; }
/// <summary>
/// Adds a new patient to the queue.
/// Patients are ordered by arrival time.
/// </summary>
/// <param name="patient">Patient to add to the queue</param>
public void Enqueue(Patient patient)
{
var newNode = new Node(patient);
if (_head == null || patient.Arrival < _head.Data.Arrival)
{
newNode.Next = _head;
_head = newNode;
Size++;
return;
}
var current = _head;
while (current.Next != null && current.Next.Data.Arrival <= patient.Arrival)
{
current = current.Next;
}
newNode.Next = current.Next;
current.Next = newNode;
Size++;
}
/// <summary>
/// Removes the next patient from the queue.
/// </summary>
/// <returns>The next patient to be treated; null if no patient is waiting</returns>
public Patient? Dequeue()
{
if (_head == null)
{
return null;
}
var patient = _head.Data;
_head = _head.Next;
Size--;
return patient;
}
/// <summary>
/// Removes the supplied patient from the queue.
/// Only patients actually waiting in this queue can be removed.
/// </summary>
/// <param name="patient">The patient to remove from the queue</param>
/// <returns>True if the patient could be removed; false otherwise</returns>
public bool Remove(Patient patient)
{
if (_head == null)
{
return false;
}
if (_head.Data == patient)
{
_head = _head.Next;
Size--;
return true;
}
var current = _head;
while (current.Next != null && current.Next.Data != patient)
{
current = current.Next;
}
if (current.Next == null)
{
return false;
}
current.Next = current.Next.Next;
Size--;
return true;
}
}