leetcode-19 删除链表的倒数第 N 个结点

题目描述:给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。

进阶:你能尝试使用一趟扫描实现吗?

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode fastNode = head;
ListNode slowNode = head;
while (n-- != 0) {
fastNode = fastNode.next;
}
if (fastNode == null) {
slowNode = head.next;
return slowNode;
}
while (fastNode.next != null) {
fastNode = fastNode.next;
slowNode = slowNode.next;
}
slowNode.next = slowNode.next.next;
return head;
}
}