PHP 数据结构

删除链表的所有节点需要遍历链表,将每个节点一一删除。它需要创建一个指向头部的临时节点,然后将头部移动到下一个头部。之后删除临时节点。重复这个过程,直到头变为空。

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

public function deleteAllNodes() {
  
  //1.创建临时节点
  $temp = new Node();

  //2。如果 head 不为空,则将 temp 作为 head 并
  // 将头移动到下一个头,然后删除临时值,
  //继续该过程直到head变为空
  while($this->head != null) {
    $temp = $this->head;
    $this->head = $this->head->next;
    $temp = null;
  }

  echo "All nodes are deleted successfully.\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;
    } else {
      $temp = new Node();
      $temp = $this->head;
      while($temp->next != null) {
        $temp = $temp->next;
      }
      $temp->next = $newNode;
    }    
  }

  //删除链表所有节点
  public function deleteAllNodes() {
    $temp = new Node();
    while($this->head != null) {
      $temp = $this->head;
      $this->head = $this->head->next;
      $temp = null;
    }
    echo "All nodes are deleted successfully.\n"; 
  }   

  //显示列表内容
  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->push_back(40);

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

//删除链表所有节点
$MyList->deleteAllNodes();

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

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

The list contains: 10 20 30 40 
All nodes are deleted successfully.
The list is empty.