当前位置 博文首页 > fareast_mzh的博客:链表删除倒数第n个节点

    fareast_mzh的博客:链表删除倒数第n个节点

    作者:[db:作者] 时间:2021-08-13 15:56

    https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/submissions/

    DeleteNode.php

    <?php
    /**
     * https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
     * Definition for a singly-linked list.
     * class ListNode {
     *     public $val = 0;
     *     public $next = null;
     *     function __construct($val = 0, $next = null) {
     *         $this->val = $val;
     *         $this->next = $next;
     *     }
     * }
     */
    
    class ListNode {
        public $val = 0;
        public $next = null;
        function __construct($val = 0, $next = null) {
            $this->val = $val;
            $this->next = $next;
        }
        private function tail() {
            for ($p = $this; $p->next != null; $p = $p->next) {}
            return $p;
        }
        public function add($val) {
            $this->tail()->next = new ListNode($val);
            return $this;
        }
        public function __toString() {
            $s = $this->val;
            for ($p = $this->next; $p != null; $p = $p->next) {
                $s .= ",".$p->val;
            }
            return $s;
        }
    }
    
    class Solution {
    
        /**
         * @param ListNode $head
         * @param Integer $n
         * @return ListNode
         */
        function removeNthFromEnd($head, $n) {
            for ($p = $head, $i = 0; $i < $n && $p != null;
                 $i++, $p = $p->next) {}
            // printf("i=%d, n=%d\n", $i, $n);
            // var_dump($p);
            if ($p == null) {
                if ($i < $n) {
                    return $head;
                }
                if ($i == $n) {
                    $toDel = $head;
                    $head = $head->next;
                    unset($toDel);
                    return $head;
                }
            }
            // prev node to delete
            for ($q = $head; $p->next != null; 
                $p = $p->next, $q = $q->next) {}
            $toDel = $q->next;
            // delete q
            $q->next = $toDel->next;
            unset($toDel);
            return $head;
        }
    }
    
    
    $list = new ListNode(1);
    $list->add(2)->add(3)->add(4)->add(5);
    echo $list.PHP_EOL;
    $s = new Solution();
    $list = $s->removeNthFromEnd($list, 3);
    echo $list.PHP_EOL;
    $list = $s->removeNthFromEnd($list, 4);
    echo $list.PHP_EOL;
    

    $ php DeleteNode.php
    1,2,3,4,5
    1,2,4,5
    2,4,5
    ?

    ?

    cs