Data structures: SplPriorityQueue

Keywords: PHP less

A normal queue is a first in, first out data structure in which elements are appended at the end of the queue and taken out from the queue head. In the priority queue, elements are given priority. When accessing an element, the element with the highest priority is taken out first. Priority queues have the behavior characteristics of largest in, first out.
It is concluded that there is a first in first out principle for ordinary queues, and a priority queue has a priority higher first out principle, which can be set;

Abstract

// 1. The ArrayAccess interface is not implemented, so it cannot operate like an array;
SplPriorityQueue implements Iterator , Countable {
  /* Method */
  public __construct ( void )

  // For the weight value, return 0 for equality, return positive integer for greater than, return negative integer for less than;
  // By default, the lower the weight value, the higher the priority
  public int compare ( mixed $priority1 , mixed $priority2 )
  public mixed extract ( void )

  //Restore to last destroyed node The test is useless;
  public void recoverFromCorruption ( void )
  public void setExtractFlags ( int $flags )
  public void insert ( mixed $value , mixed $priority )

  public int count ( void )
  public mixed current ( void )
  public bool isEmpty ( void )
  public mixed key ( void )
  public void next ( void )
  public void rewind ( void )
  public mixed top ( void )
  public bool valid ( void )
}

Example

class PQtest extends SplPriorityQueue
{
  //Override the parent class, change its priority rule to the smaller the weight value, the higher the priority;
  public function compare($priority1, $priority2)
  {
    if ($priority1 === $priority2) return 0;
    return $priority1 > $priority2 ? -1 : 1;
  }
}

$pq = new PQtest();

// Set value and priority value
$pq->insert('a', 10);
$pq->insert('b', 1);
$pq->insert('c', 8);

/**
 * Set element out mode
 * SplPriorityQueue::EXTR_DATA Extract value only
 * SplPriorityQueue::EXTR_PRIORITY Extract priority only
 * SplPriorityQueue::EXTR_BOTH Extract array contains values and priorities
 */
$pq->setExtractFlags(PQtest::EXTR_BOTH);

//A node is taken out from the top, and the node below the node is moved up to the top node;
print_r(
  $pq->extract()
);
/*
  [data] => b
  [priority] => 1
 */

$pq->recoverFromCorruption();

//Take out the top node
print_r(
  $pq->extract()
);

/*
  [data] => c
  [priority] => 8
 */

// Restore from previous node No effect?
$pq->recoverFromCorruption();

print_r(
  $pq->current()
);

$pq->rewind();
while($pq->valid()){
  print_r($pq->current());
  echo PHP_EOL;
  $pq -> next();
}

Posted by big-dog on Wed, 06 Nov 2019 15:13:03 -0800