给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
示例 1:

输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1
输出:[]
示例 3:
输入:head = [1,2], n = 1
输出:[1]
增加哨兵节点,采用双指针的方式去查询要删除的值,使该值上一个指针指向该值下一个指针。
哨兵节点,其实就是一个附加在原链表最前面用来简化边界条件的附加节点,它的值域不存储任何东西,只是为了操作方便而引入。
go代码:
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func removeNthFromEnd(head *ListNode, n int) *ListNode {
result := &ListNode{}
result.Next = head
var pre *ListNode
cur := result
i := 1
for head != nil {
if i >= n {
pre = cur
cur = cur.Next
}
head = head.Next
i++
}
pre.Next = pre.Next.Next
return result.Next
}
php代码:
/**
* 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 Solution {
/**
* @param ListNode $head
* @param Integer $n
* @return ListNode
*/
function removeNthFromEnd($head, $n) {
$list = new ListNode(null);
$list->next = $head;
$first = $head;
$i =0;
while($i<$n-1) {
$first = $first->next;
$i++;
}
$new_list = $this->getNode($list,$first);
$new_list->next = $new_list->next->next;
return $list->next;
}
function getNode($list,$first){
if($first->next->val === null)
{
return $list;
}
$list = $list->next;
$first = $first->next;
return $this->getNode($list,$first);
}
}
&spm=1001.2101.3001.5002&articleId=114120045&d=1&t=3&u=10115b316b7045388f31c8384df348ef)
3124

被折叠的 条评论
为什么被折叠?



