Ответы пользователя по тегу Алгоритмы
  • PHP: как в односвязном списке удалить из середины элемент по его номеру?

    iMedved2009
    @iMedved2009
    Не люблю людей
    <?php
    class Node
    {
        public $data;
        public $next;
    
        function __construct($data, $next = null)
        {
            $this->data = $data;
            $this->next = $next;
        }
    }
    
    class LinkedList{
    
        public $head = null;
    
        public function push(Node $node){
            if($this->head == null){
                $this->head = $node;
                return $this;
            }
    
            $current = $this->head;
            while($current->next != null) {
                $current = $current->next;
            }
    
            $current->next = $node;
            return $this;
        }
    
        public function cut(int $index){
            if($index == 0){
                $this->head = $this->head->next;
                return $this;
            }
    
            $i = 0;
            $previous = null;
            $current = $this->head;
            do {
                if($i == $index){
                    $previous->next = $current->next;
                    return $this;
                }
                $previous = $current;
                $i++;
            }while(($current = $current->next) != null);
    
            throw new Exception('Надо эксепшен что бы out of bounds');
        }
    
        public function printList()
        {
            if(!$this->head){
                echo 'empty list'.PHP_EOL;
                return $this;
            }
            $current = $this->head;
    
            echo $current->data.' -> ';
            while (($current = $current->next)) {
                echo $current->data;
    
                if($current->next) {
                    echo ' -> ';
                }
            }
    
            echo PHP_EOL;
    
            return $this;
        }
    
    }
    
    $linkedList = new LinkedList();
    
    $linkedList
        ->push(new Node('Ari'))
        ->push(new Node('Malcolm'))
        ->push(new Node('Pete'))
        ->push(new Node('Ricky'))
        ->push(new Node('Sean'));
    $linkedList
        ->printList()
        ->cut(2)
        ->printList()
        ->cut(1)
        ->printList()
        ->cut(10);
    Ответ написан
    2 комментария