是否可以在php中链接列表的中间插入。如果是,有人可以向我提供实现它的函数的代码吗?
答案 0 :(得分:1)
是的,这是可能的。
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
}
这当然是伪代码,因为您没有提供任何示例代码。