我正在尝试使用 PHP 实现一个链表。我已经完成了其中的一部分,但是,我不确定我的代码是否正确。您能否建议如何在指定索引处添加/删除特定节点?
请参考以下代码:(共3个文件)
1) [ListNode.class.php]
我定义的节点结构:
<?php
class ListNode
{
protected $next; // Next node in the list
protected $value; // Value of the node
// Constructor
// Input: Value of the node
public function __construct($value)
{
$this->value = $value;
$this->next = NULL;
}
public function __get($name)
{
return $this->$name;
}
public function __set($name, $value)
{
$this->$name = $value;
}
// Return the node as string
public function toString()
{
return $this->value . "\n";
}
}
2) [LinkList.class.php]
链表和我没有完成的操作:
<?php
require('ListNode.class.php');
class LinkedList
{
protected $first; // First node of the list
protected $last; // Last node of the list
protected $count; // Total numbers of nodes in the list
// Constructor
// Input: Array of values (Optional)
public function __construct($values = array())
{
$this->first = null;
$this->last = null;
$this->count = 0;
foreach ($values as $value) {
$this->add($value);
}
}
public function isEmpty()
if ($this->sizeOf() !== 0)
return ($this->first == NULL);
}
// Add a node at the beginning of the list
public function add($value)
{
$link = new ListNode($value);
$link->next = $this->first;
$this->first = &$link;
if($this->last == NULL)
$this->last = &$link;
$this->count++;
}
// Add a node at the specified index
public function addAtIndex($value, $index)
{
}
// Remove a node at the end of the list
public function remove()
{
if($this->first != NULL)
{
if($this->first->next == NULL)
{
$this->first == NULL;
$this->cout--;
}
else
{
$previous = $this->first;
$current = $this->first->next;
while($current->next != NULL)
{
$previous = $current;
$current = $current->next;
$previous->next = NULL;
$this->count--;
}
}
// Remove a node at the specified index
public function removeAtIndex($index)
{
}
// Return the value of the first node
public function getNode()
{
}
// Return the value of the node at the specified index
public function getNodeAtIndex($index)
{
if($index <= $this->count)
{
$current = $this->firstNode;
$pos = 1;
while($pos != $index)
{
if($current->next == NULL)
return null;
else
$current = $current->next;
$pos++;
}
return $current->value;
}
else
return NULL;
}
// Return the number of nodes
public function sizeOf()
{
return $this->count;
}
// Return the list as string
public function toString()
{
$list = "";
$node = $this->first;
while ($node != null) {
$list .= $node->toString();
$node = $node->next;
}
return $list;
}
}