单向链表PHP简单实现
class Node
{
public int|null $id;
public mixed $data;
public Node|null $next;
public function __construct($id = 0, $data = null)
{
$this->id = $id;
$this->data = $data;
$this->next = null;
}
}
class SingleLinkList
{
private Node|null $head = null;
public function __construct($id = 0, $data = null)
{
$this->head = new Node($id, $data);
}
public function addLink(Node $node)
{
if ($this->isLinkEmpty()) {
return false;
}
$current = $this->head;
while ($current->next != null) {
if ($current->next->id == $node->id) {
echo "链表中已存在id={$node->id}的节点!";
return false;
}
if ($current->next->id > $node->id) {
break;
}
$current = $current->next;
}
$node->next = $current->next;
$current->next = $node;
return true;
}
public function delLink($id)
{
if ($this->isLinkEmpty()) {
return false;
}
$current = $this->head;
$exist = false;
if($current->id == $id){
$this->head = $current->next;
return true;
}
while ($current->next != null) {
if ($current->next->id == $id) {
$exist = true;
break;
}
$current = $current->next;
}
if ($exist) {
$current->next = $current->next->next;
return true;
} else {
echo "链表中没有找到id={$id}的节点!";
return false;
}
}
public function updateNodeData($id, $data)
{
if ($this->isLinkEmpty()) {
return false;
}
$current = $this->head;
$exist = false;
while ($current->next != null) {
if ($current->id == $id) {
$exist = true;
break;
}
$current = $current->next;
}
if ($exist) {
$current->data = $data;
return true;
} else {
echo "链表中没有找到id={$id}的节点!";
return false;
}
}
public function getLinkLength()
{
if ($this->isLinkEmpty()) {
return 0;
}
$current = $this->head;
$i = 0;
while ($current->next != null) {
$i++;
$current = $current->next;
}
return $i;
}
public function clear()
{
$this->head = null;
}
public function isLinkEmpty()
{
if ($this->head == null) {
echo '链表为空!';
}
return false;
}
public function getIndex($id)
{
if ($this->isLinkEmpty()) {
return false;
}
$current = $this->head;
$exist = false;
while ($current->next != null) {
if ($current->id == $id) {
$exist = true;
break;
}
$current = $current->next;
}
if ($exist) {
return $current;
} else {
echo "链表中没有找到id={$id}的节点!";
return false;
}
}
}
$lists = new SingleLinkList();
$lists->addLink(new Node(1, 1));
$lists->addLink(new Node(1, 1));
$lists->addLink(new Node(5, 1));
$lists->addLink(new Node(4, 1));
$lists->addLink(new Node(3, 1));
dump($lists->delLink(0));
dd($lists);