Implementing a queue using linked list

As we did with the stack implementation, we are going to use our linked list implementation in Chapter 3, Using Linked Lists, to implement the queue here. We can use the insert() method to ensure that we are always inserting at the end. We can use deleteFirst() for a dequeue operation and getNthNode() for a peek operation. Here is the sample implementation of a queue using a linked list:

class AgentQueue implements Queue { 

private $limit;
private $queue;

public function __construct(int $limit = 20) {
$this->limit = $limit;
$this->queue = new LinkedList();
}

public function dequeue(): string {

if ($this->isEmpty()) {
throw new UnderflowException('Queue is empty');
} else {
$lastItem = $this->peek();
$this->queue->deleteFirst();
return $lastItem;
}
}

public function enqueue(string $newItem) {

if ($this->queue->getSize() < $this->limit) {
$this->queue->insert($newItem);
} else {
throw new OverflowException('Queue is full');
}
}

public function peek(): string {
return $this->queue->getNthNode(1)->data;
}

public function isEmpty(): bool {
return $this->queue->getSize() == 0;
}

}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset