php實現一個單鏈表

  單鏈表,節點只有一個指針域的鏈表。節點包括數據域和指針域。

  因此用面向對象的思維,節點類的屬性就有兩個:一個data(表示存儲的數據),一個指針next(鏈表中指向下一個節點)。

  鏈表一個很重要的特性,就是這個頭節點$head。它絕對不能少,每次遍歷都要從它開始,並且不能移動頭節點,應該用一個變量去代替他移動。腦袋裏要有鏈表的結構。這是關鍵。

  來一段代碼:

<?php

class Node{
    public $data = '';
    public $next = null;
    function __construct($data)
    {
        $this->data = $data;
    }
}


// 鏈表有幾個元素
function countNode($head){
    $cur = $head;
    $i = 0;
    while(!is_null($cur->next)){
        ++$i;
        $cur = $cur->next;
    }
    return $i;
}

// 增加節點
function addNode($head, $data){
    $cur = $head;
    while(!is_null($cur->next)){
        $cur = $cur->next;
    }
    $new = new Node($data);
    $cur->next = $new;

}

// 緊接着插在$no後
function insertNode($head, $data, $no){
    if ($no > countNode($head)){
        return false;
    }
    $cur = $head;
    $new = new Node($data);
    for($i=0; $i<$no;$i++){
        $cur = $cur->next;
    }
    $new->next = $cur->next;
    $cur->next = $new;

}

// 刪除第$no個節點
function delNode($head, $no){
    if ($no > countNode($head)){
        return false;
    }
    $cur = $head;
    for($i=0; $i<$no-1; $i++){
        $cur = $cur->next;
    }
    $cur->next = $cur->next->next;

}

// 遍歷鏈表
function showNode($head){
    $cur = $head;
    while(!is_null($cur->next)){
        $cur = $cur->next;
        echo $cur->data, '<br/>';
    }
}

$head = new Node(null);// 定義頭節點


addNode($head, 'a');
addNode($head, 'b');
addNode($head, 'c');

insertNode($head, 'd', 0);

showNode($head);

echo '<hr/>';

delNode($head, 2);

showNode($head);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章