定义一个链表指向原链表
使用快慢结点的思路,一个快结点先走n步,然后慢结点和快结点保持n的距离前进,同时有一个结点指向慢结点的前一个
<?php
/*class ListNode{
var $val;
var $next = NULL;
function __construct($x){
$this->val = $x;
}
}*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
function removeNthFromEnd( $head , $n )
{
// write code here
if($n == 0){
return $head;
}
$res = new ListNode(-1);
$res->next = $head;
$pre = $res;
$curr = $head;
$moveList = $head;
for($i = 0; $i < $n ; $i++){
$moveList = $moveList->next;
}
while($moveList != null){
$moveList = $moveList->next;
$pre = $curr;
$curr = $curr->next;
}
$pre->next = $curr->next;
return $res->next;
}