Leetcode基础刷题之PHP解析(19. Remove Nth Node From End of List)

栏目: PHP · 发布时间: 5年前

内容简介:2019-6-27 星期四 开始吧

2019-6-27 星期四 开始吧

Leetcode基础刷题之 PHP 解析(18. 4Sum)

Leetcode基础刷题之PHP解析(19. Remove Nth Node From End of List)

给定一个链表和一个随机数(随机数在可操作范围),从链表的后面开始,移除倒数第n个节点,返回新的链表。

删除倒数第n个节点,也就是删除链表第Length-n+1个节点,所以第一步先求出链表的长度,第二步就是开始正式找删除节点了,通过指针的移动,先确认Lenght-n的位置,这个位置的下一个位置就是待删除的节点,我们只需要把这个位置的next指针指向他的->next->next即可。

/**
 * Definition for a singly-linked list.
 * class ListNode {
 *     public $val = 0;
 *     public $next = null;
 *     function __construct($val) { $this->val = $val; }
 * }
 */
class Solution {

    /**
     * @param ListNode $head
     * @param Integer $n
     * @return ListNode
     */
   
    function removeNthFromEnd($head, $n) {
      $temp->next=$head;
      $node=$head;
        $count=0;
        while($node !=null){
            $count++;
            $node=$node->next;
        }
        $count -=$n;
        $node=$temp;
        
        while($count>0){
            $count--;
            $node=$node->next;
        }
        $node->next=$node->next->next;
        return $temp->next;
    }
}

Github整理地址 : https://github.com/wuqinqiang/leetcode-php


以上所述就是小编给大家介绍的《Leetcode基础刷题之PHP解析(19. Remove Nth Node From End of List)》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Practice of Programming

The Practice of Programming

Brian W. Kernighan、Rob Pike / Addison-Wesley / 1999-2-14 / USD 49.99

With the same insight and authority that made their book The Unix Programming Environment a classic, Brian Kernighan and Rob Pike have written The Practice of Programming to help make individual progr......一起来看看 《The Practice of Programming》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试