使用PHP创建一个双向链表

创建双向链表

element = $element;
        $this->next = $next;
        $this->previous = $previous;

    }

}


class LinkedList{

    public $head;

    public function __construct($head = "head")
    {
        $this->head = new Node($head);
    }

    /**
     * 查找元素是否在链表中
     * @param $item
     * @return Node|null
     */
    public function find($item)
    {
        $currNode = $this->head;

        while ($currNode->element != $item){
            $currNode = $currNode->next;
        }

        return $currNode;
    }

    /**
     * 向链表中插入一个元素
     * @param $newElement
     * @param $item
     */
    public function insert($newElement , $item)
    {
        $newNode = new Node($newElement);
        $current = $this->find($item);

        $newNode->next = $current->next;
        $newNode->previous = $current;
        $current->next = $newNode;

    }

    public function display()
    {
        $currNode = $this->head;

        while ($currNode != null){
            echo $currNode->next->element;
            echo "
"; $currNode = $currNode->next; } } /** * 从链表中删除一个元素 * 首先找到待删除元素的前一个元素 * @param $item */ public function remove($item) { $currNode = $this->find($item); if($currNode->next != null){ $currNode->previous->next = $currNode->next; $currNode->next->previous = $currNode->previous; $currNode->next = null; $currNode->previous = null; } } /** * 找到置顶元素的链表前一个元素(在双向链表中不需要) * @param $item * @return Node|null */ public function findPrevious($item) { $currNode = $this->head; while (($currNode->next != null) && ($currNode->next->element != $item)){ $currNode = $currNode->next; } return $currNode; } /*** * 查找双向链表的最后一个元素 * @return Node|null */ public function findLast() { $currNode = $this->head; while ($currNode->next != null){ $currNode = $currNode->next; } return $currNode; } public function disReverse() { $currNode = $this->findLast(); while ( $currNode->previous != null){ echo $currNode->element; echo "
"; $currNode = $currNode->previous; } } } $llist = new LinkedList(); $llist->insert("Conway","head"); $llist->insert("Russellville","Conway"); $llist->insert("Carlisle","Russellville"); $llist->insert("Alma","Carlisle"); $llist->display(); $llist->remove("Conway"); $llist->display(); $llist->disReverse();

你可能感兴趣的:(使用PHP创建一个双向链表)