标题:19删除链表的倒数第N个结点-中等
题目
给你一个链表,删除链表的倒数第
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]
提示
- 链表中结点的数目为
sz
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
代码Java
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode p = head;
ListNode s = head;
while (p != null) {
if (n < 0) {
s = s.next;
}
p = p.next;
n--;
}
if (n == 0)
return head.next;
else {
s.next = s.next.next;
return head;
}
}