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(true) {
      echo $temp->data." ";
      $temp = $temp->next;
      if($temp == $this->head)
        break;        
    }
    echo "\n";
  } else {
    
    //3。如果临时节点在开始时为空,
    //列表为空
    echo "The list is empty.\n";
  }
} 

下面是一个完整的程序,使用上面讨论的概念来遍历循环单链表并显示其内容.

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

class LinkedList {
  public $head;

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

  //显示列表内容
  public function PrintList() {
    $temp = new Node();
    $temp = $this->head;
    if($temp != null) {
      echo "The list contains: ";
      while(true) {
        echo $temp->data." ";
        $temp = $temp->next;
        if($temp == $this->head)
          break;        
      }
      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