php实现一个单链表

  单链表,节点只有一个指针域的链表。节点包括数据域和指针域。

  因此用面向对象的思维,节点类的属性就有两个:一个data(表示存储的数据),一个指针next(链表中指向下一个节点)。

  链表一个很重要的特性,就是这个头节点$head。它绝对不能少,每次遍历都要从它开始,并且不能移动头节点,应该用一个变量去代替他移动。脑袋里要有链表的结构。这是关键。

  来一段代码:

  

 1 <?php
 2 
 3 class Node{
 4     public $data = '';
 5     public $next = null;
 6     function __construct($data)
 7     {
 8         $this->data = $data;
 9     }
10 }
11 
12 
13 // 链表有几个元素
14 function countNode($head){
15     $cur = $head;
16     $i = 0;
17     while(!is_null($cur->next)){
18         ++$i;
19         $cur = $cur->next;
20     }
21     return $i;
22 }
23 
24 // 增加节点
25 function addNode($head, $data){
26     $cur = $head;
27     while(!is_null($cur->next)){
28         $cur = $cur->next;
29     }
30     $new = new Node($data);
31     $cur->next = $new;
32 
33 }
34 
35 // 紧接着插在$no后
36 function insertNode($head, $data, $no){
37     if ($no > countNode($head)){
38         return false;
39     }
40     $cur = $head;
41     $new = new Node($data);
42     for($i=0; $i<$no;$i++){
43         $cur = $cur->next;
44     }
45     $new->next = $cur->next;
46     $cur->next = $new;
47 
48 }
49 
50 // 删除第$no个节点
51 function delNode($head, $no){
52     if ($no > countNode($head)){
53         return false;
54     }
55     $cur = $head;
56     for($i=0; $i<$no-1; $i++){
57         $cur = $cur->next;
58     }
59     $cur->next = $cur->next->next;
60 
61 }
62 
63 // 遍历链表
64 function showNode($head){
65     $cur = $head;
66     while(!is_null($cur->next)){
67         $cur = $cur->next;
68         echo $cur->data, '<br/>';
69     }
70 }
71 
72 $head = new Node(null);// 定义头节点
73 
74 
75 addNode($head, 'a');
76 addNode($head, 'b');
77 addNode($head, 'c');
78 
79 insertNode($head, 'd', 0);
80 
81 showNode($head);
82 
83 echo '<hr/>';
84 
85 delNode($head, 2);
86 
87 showNode($head);
原文地址:https://www.cnblogs.com/firstForEver/p/5245534.html