<?php
class Node
{
public $value;
public $next;
public function __construct($value = null)
{
$this->value = $value;
$this->next = null;
}
}
class SingleLinkList
{
public $head;
public function __construct()
{
$this->head = new Node();
}
public function count()
{
$current = $this->head;
$i = 0;
while (!is_null($current->next)) {
$i++;
$current = $current->next;
}
return $i;
}
public function add($value)
{
$current = $this->head;
while (!is_null($current->next)) {
$current = $current->next;
}
$newNode = new Node($value);
$current->next = $newNode;
}
public function insert($no, $data)
{
if ($no > $this->count())
return false;
$current = $this->head;
$newNode = new Node($data);
for ($i = 0; $i < $no; $i++) {
$current = $current->next;
}
$newNode->next = $current->next;
$current->next = $newNode;
return true;
}
public function update($no, $data)
{
if ($no > $this->count())
return false;
$current = $this->head;
for ($i = 0; $i < $no; $i++) {
$current = $current->next;
}
$current->value = $data;
return true;
}
public function del($no)
{
if ($no > $this->count())
return false;
$current = $this->head;
for ($i = 0; $i < $no - 1; $i++) {
$current = $current->next;
}
$current->next = $current->next->next;
return true;
}
public function show()
{
$current = $this->head;
while (!is_null($current->next)) {
$current = $current->next;
echo $current->value . " ";
}
}
}
$a = new SingleLinkList();
$a->add('a');
$a->add('b');
$a->add('c');
$a->add('d');
$a->add('e');
$a->add('f');
$a->add('g');
var_dump($a->insert(1, "hello"));
var_dump($a->del(2));
var_dump($a->update(2, 'world'));
$a->show();
var_dump($a->head);
php 实现单链表的增删改查
最新推荐文章于 2024-06-27 16:39:17 发布