Leetcode基础刷题之PHP解析(19. Remove Nth Node From End of List)
2019-6-27 星期四 开始吧
上一题链接Leetcode基础刷题之PHP解析(18. 4Sum)
题目描述
给定一个链表和一个随机数(随机数在可操作范围内),从链表的后面开始,移除倒数第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
No Comments