1. 程式人生 > >php實現循環鏈表

php實現循環鏈表

ren this spa code date style 下午 null nbsp

<?php
/**
 * php實現鏈表
 * Date: 2018/5/18
 * Time: 下午5:59
 */

class Node
{
    public $nodeId = 0;
    public $left = 0;
    public $right = 0;

    public function __construct($nodeId, $left, $right)
    {
        $this->nodeId = $nodeId;
        $this->left = $left;
        $this->right = $right
; } } class ListArr { private $list = null; public function construct() { } //創造一個n長度鏈表 public function createList($n) { if ($n <= 0) { return false; } for ($i = 0; $i < $n; $i++) { if ($i == 0) {
$node = new Node(0, $n - 1, 1); } elseif ($i == $n - 1) { $node = new Node($n - 1, $n - 2, 0); } else { $node = new Node($i, $i - 1, $i + 1); } $this->list[$i] = $node; } } //遍歷鏈表 public function iteratorList() {
$total = count($this->list); //鏈表長度 $strRet = ‘‘; for ($i = 0; $i < $total; $i++) { $node = $this->list[$i]; echo "current node : {$node->left}->{$node->nodeId}->{$node->right}\n"; } echo $strRet; } //查找某一節點 public function findNode($n) { if ($n < 0 ) { return false; } $total = count($this->list); if ($n > $total) { $n = $n % $total; $node = $this->list[$n - 1]; } else { $node = $this->list[$n - 1]; } echo "current Node is {$node->nodeId} left is {$node->left} right is {$node->right}\n"; } } $list = new ListArr(); $list->createList(5); $list->findNode(3); $list->findNode(6); $list->iteratorList();

php實現循環鏈表