PHP 数据结构

在处理链表时,计算链表中的节点非常有用。它需要创建一个指向列表头部的临时节点和一个名为i的变量,初始值为0。如果临时节点不为空,则将i增加1并使用 temp next 移动到下一个节点。重复该过程,直到临时节点变为空。 i 的最终值将是链表中节点的总数。

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

public function countNodes() {
  
  //1.创建一个指向 head 的临时节点
  $temp = new Node();
  $temp = $this->head;
  
  //2。创建一个变量来计算节点数
  $i = 0;

  //3。如果临时节点不为空则增加
  // i减1并移动到下一个节点,重复
  //直到temp变为null的过程
  while($temp != null) {
    $i++;
    $temp = $temp->next;
  }

  //4。返回计数
  return $i;  
}  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

下面是一个完整的程序,它使用了上面讨论的计算链表节点总数的概念。

<?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 countNodes() {
    $temp = new Node();
    $temp = $this->head;
    $i = 0;
    while($temp != null) {
      $i++;
      $temp = $temp->next;
    }
    return $i;  
  }  

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

//链表中的节点数
echo "No. of nodes: ".$MyList->countNodes();
?>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75

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

The list contains: 10 20 30 40
No. of nodes: 4
  • 1
  • 2