我想使用PHP OOP在特定索引的链表中插入节点... 我在开始时插入节点的代码和最后插入节点的代码如下
//top class for creating node
class ListNode
{
public $data;
public $next;
function __construct($data)
{
$this->data = $data;
$this->next = NULL;
}
function readNode()
{
return $this->data;
}
}
//main class which will insert node
class LinkList
{
private $firstNode;
private $lastNode;
private $count;
function __construct()
{
$this->firstNode = NULL;
$this->lastNode = NULL;
$this->count = 0;
}
//insertion in start of linklist
public function insertFirst($data)
{
$link = new ListNode($data);
$link->next = $this->firstNode;
$this->firstNode = &$link;
/* If this is the first node inserted in the list
then set the lastNode pointer to it.
*/
if($this->lastNode == NULL)
$this->lastNode = &$link;
$this->count++;
}
//insertion at the last of linklist
public function insertLast($data)
{
if($this->firstNode != NULL)
{
$link = new ListNode($data);
$this->lastNode->next = $link;
$link->next = NULL;
$this->lastNode = &$link;
$this->count++;
}
else
{
$this->insertFirst($data);
}
}
}
答案 0 :(得分:0)
将此添加到ListNode
function addAtIndex($index, $data) {
if ($index != 0) {
//pass through links till you hit the index
$next->addAtIndex($index-1, $data)
} else {
$node = new ListNode($data);
$node->next = $this->next;
$this->next = &node;
}
}
这样打电话:
$firstNode->addAtIndex($index, $data)
未经测试......只是一个想法
答案 1 :(得分:0)
你可以做些什么来保持OOP在 ListNode 类上创建一些方法,如 insertBeforeMe 和 insertAfterMe 。正如@Flame指出的那样,不是 LinkList 商务
答案 2 :(得分:0)
通过以下代码修复它
public function insert($NewItem,$key){
if($key == 0){
$link = new ListNode($NewItem);
$link->next = $this->firstNode;
$this->firstNode = &$link;
/* If this is the first node inserted in the list
then set the lastNode pointer to it.
*/
if($this->lastNode == NULL)
$this->lastNode = &$link;
$this->count++;
}
else{
$link = new ListNode($NewItem);
$current = $this->firstNode;
$previous = $this->firstNode;
for($i=0;$i<$key;$i++)
{
$previous = $current;
$current = $current->next;
}
$previous->next = $link;
$link->next = $current;
$this->count++;
}
}