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);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM