在php中插入链接列表的中间
可能重复:在php中插入链接列表的中间,php,list,linked-list,Php,List,Linked List,可能重复: 可以在PHP中插入链表中间。如果是,请有人向我提供实现它的函数的代码吗?是的,这是可能的 function insertIntoMiddle($LinkedList, $NewItem) { // we will use current as a pointer to the current position in our list // if we arrive at the middle, we insert the $NewItem $currentI
可以在PHP中插入链表中间。如果是,请有人向我提供实现它的函数的代码吗?是的,这是可能的
function insertIntoMiddle($LinkedList, $NewItem)
{
// we will use current as a pointer to the current position in our list
// if we arrive at the middle, we insert the $NewItem
$currentIndex = 0;
$currentItem = $LinkedList->getFirstItem();
// calculate the middle of your list
$middleIndex = floor($LinkedList->getLength() / 2);
// Loop over the list until you get the item in the middle
while (++$currentIndex < $middleIndex)
{
$currentItem = $currentItem->getNextItem();
}
// insert the $NewItem between $currentItem and the next
$NewItem->setNextItem($currentItem->getNextItem());
$currentItem->setNextItem($NewItem);
// also setPreviousItem() if you have linked your list both ways
}
函数插入中间($LinkedList,$NewItem)
{
//我们将使用current作为指向列表中当前位置的指针
//如果到达中间位置,则插入$NewItem
$currentIndex=0;
$currentItem=$LinkedList->getFirstItem();
//计算你名单的中间部分
$middleIndex=floor($LinkedList->getLength()/2);
//在列表中循环,直到您在中间得到该项
而(++$currentIndex<$middleIndex)
{
$currentItem=$currentItem->getNextItem();
}
//在$currentItem和下一个项目之间插入$NewItem
$NewItem->setNextItem($currentItem->getNextItem());
$currentItem->setNextItem($NewItem);
//如果您已双向链接列表,也可以设置PreviousItem()
}
这当然是伪代码,因为您没有提供任何示例代码。您当前的LinkedList是什么样子的?您使用的是SPL链接列表吗?或者您是否编写了某种自制代码?