云迈博客

您现在的位置是:首页 > 后端开发 > PHP > 正文

PHP

[Review] Implement SinglyLinkedList in PHP

wsinbol2020-10-18PHP323
Talkischeap,justshowthecode.ThepageisbasedonHere.

Talk is cheap, just show the code. The page is based on Here.

1. class Node:

class Node{
    private $data;
    private $_next;

    public function __construct($val){
        $this->data = $val;
        $this->_next = null;
    }
}

2. class SinglyLinkedList:

class SinglyLinkedList{
    private $_head;
    public function __construct(){
        $this->_head = null;
    }
}

3. Options:

class SinglyLinkedList{
    //code skips, from #2

    public function insert_first($val){
        $new_node = new Node($val);
        $new_node->_next = $this->_head;
        $this->_head = $new_node;
    }

    public function insert_last($val){
        $new_node = new Node($val);
        $cur = $this->_head;
        if($cur == null){
            $cur = $new_node;
        }else{
            while($cur->_next != null){
                $cur = $cur->_next;
            }
            $cur->_next = $new_node;
        }
    }

    public function insert_after_target($target_node, $val){
        $new_node = new Node($val);
        $new_node->_next = $target_node->_next;
        $target_node->_next = $new_node;
    }

    public function insert_before_target($target_node, $val){
        $new_node = new Node($val);
        $cur = $this->_head;
        if($target_node == $cur){
            $new_node->_next = $cur;
            $this->_head = $new_node;
        }

        $nxt = $cur->_next;
        while($nxt && $nxt->data != $target_node->data){
            $cur = $nxt;
            $nxt = $nxt->_next;
        }

        if($nxt->data == $target_node->data){
            $new_node->_next = $nxt;
            $cur->_next = $new_node;
        }else{
            return null;
        }

    }

    public function delete_current_node($node){

    }

    public function delete_before_node($node){

    }

    public function delete_after_node($node){
        $node->_next = $node->_next->_next;
    }

    public function find_value($val){
        $cur = $this->_head;
        while($cur and $cur->data != $val){
            $cur = $cur->_next;
        }
        return $cur ?? true : false;
    }
}

发表评论

评论列表

  • 这篇文章还没有收到评论,赶紧来抢沙发吧~