在php中的链接列表中间插入


insertion in middle of a linked list in php

可能重复:
PHP在特定索引处插入

是否可以在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
}

这当然是伪代码,因为您没有提供任何示例代码。