Skip to content

Commit 6c25a20

Browse files
committed
剑指OfferII 021. 删除链表的倒数第n个结点
1 parent 883f5b8 commit 6c25a20

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.gatsby.offerII;
2+
3+
import com.gatsby.ListNode;
4+
5+
/**
6+
* @ClassName: _21RemoveNthFromEnd
7+
* @Description: 剑指 Offer II 021. 删除链表的倒数第 n 个结点
8+
* <p>
9+
* 1 -> 2 -> 3 -> 4 -> 5
10+
* @author: Gatsby
11+
* @date: 2022/7/14 13:38
12+
*/
13+
14+
public class _21RemoveNthFromEnd {
15+
public ListNode removeNthFromEnd(ListNode head, int n) {
16+
ListNode dummy = new ListNode(-1);
17+
dummy.next = head;
18+
ListNode fast = dummy;
19+
ListNode slow = dummy;
20+
while (n-- != 0) {
21+
fast = fast.next;
22+
}
23+
24+
while (fast != null && fast.next != null) {
25+
fast = fast.next;
26+
slow = slow.next;
27+
}
28+
29+
slow.next = slow.next.next;
30+
return dummy.next;
31+
}
32+
}
33+
34+

0 commit comments

Comments
 (0)