Beispiel #1
0
 /**
  * Merges two sorted linked lists non recursively
  * @param DoubleLinkedList $first
  * @param DoubleLinkedList $second
  * @return DoubleLinkedList
  */
 private function merge(DoubleLinkedList $first, DoubleLinkedList $second)
 {
     $listToReturn = new DoubleLinkedList();
     if ($first === null) {
         $listToReturn = $second;
     } elseif ($second === null) {
         $listToReturn = $first;
     } else {
         while (!$first->isEmpty() && !$second->isEmpty()) {
             if ($first->getBottom()->getData() < $second->getBottom()->getData()) {
                 $listToReturn->push($first->getBottom()->getData());
                 $first->delete();
             } else {
                 $listToReturn->push($second->getBottom()->getData());
                 $second->delete();
             }
         }
         while (!$first->isEmpty()) {
             $listToReturn->push($first->getBottom()->getData());
             $first->delete();
         }
         while (!$second->isEmpty()) {
             $listToReturn->push($second->getBottom()->getData());
             $second->delete();
         }
     }
     return $listToReturn;
 }