PHP 数据结构

遍历双向链表非常容易。它需要创建一个指向列表头部的临时节点。如果 temp 节点不为空,则显示其内容并使用 temp next 移至下一个节点。重复该过程,直到临时节点变为空。如果临时节点在开始时为空,则列表不包含任何项目。

函数PrintList就是为此目的而创建的。这是一个3步过程

public function PrintList() {
  
  //1.创建一个指向 head 的临时节点
  $temp = new Node();
  $temp = $this->head;
  
  //2。如果临时节点不为空继续
  //显示内容并移动到
  //下一个节点,直到温度变为空
  if($temp != null) {
    echo "The list contains: ";
    while($temp != null) {
      echo $temp->data." ";
      $temp = $temp->next;
    }
    echo "\n";
  } else {
    
    //3。如果临时节点在开始时为空,
    //列表为空
    echo "The list is empty.\n";
  }
}  

下面是一个完整的程序,它使用上面讨论的概念来遍历双向链表并显示其内容。

<?php
//节点结构
class Node {
  public $data;
  public $next;
  public $prev;
}

class LinkedList {
  public $head;

  public function __construct(){
    $this->head = null;
  }
  
  //在列表末尾添加新元素
  public function push_back($newElement) {
    $newNode = new Node();
    $newNode->data = $newElement;
    $newNode->next = null;
    $newNode->prev = null; 
    if($this->head == null) {
      $this->head = $newNode;
    } else {
      $temp = new Node();
      $temp = $this->head;
      while($temp->next != null) {
        $temp = $temp->next;
      }
      $temp->next = $newNode;
      $newNode->prev = $temp;
    }    
  }

  //显示列表内容
  public function PrintList() {
    $temp = new Node();
    $temp = $this->head;
    if($temp != null) {
      echo "The list contains: ";
      while($temp != null) {
        echo $temp->data." ";
        $temp = $temp->next;
      }
      echo "\n";
    } else {
      echo "The list is empty.\n";
    }
  }   
};

//测试代码
$MyList = new LinkedList();

//在列表末尾添加三个元素。
$MyList->push_back(10);
$MyList->push_back(20);
$MyList->push_back(30);

//遍历显示列表内容。
$MyList->PrintList();
?>

上面的代码将给出以下输出:

The list contains: 10 20 30