题解 | #删除链表的倒数第n个节点#
删除链表的倒数第n个节点
https://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6
<?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 ) { if($n < 1 || $head == null){ return null; } $first = $head; $second = $head; $pre = null; for($i=0;$i < $n-1;$i++){ $first = $first->next; } while($first->next != null){ $first = $first->next; $pre = $second; $second = $second->next; } // 判断pre是否是null if($pre != null){ $pre->next = $second->next; return $head; } return $second->next; }
通过二指针法找到倒数第n个节点,注意维护一个pre节点指向倒数第n-1个节点。判断pre是否是null,如果是,代表要删除第一个,直接返回第二个节点的next;否则pre->next = second->next