Skip to content

Commit f60d636

Browse files
committed
Add solution 019
1 parent d5396b9 commit f60d636

File tree

4 files changed

+75
-23
lines changed

4 files changed

+75
-23
lines changed

.gitignore

-23
This file was deleted.

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ Complete solutions to Leetcode problems, updated daily.
2020

2121
| # | Title | Tags |
2222
|---|---|---|
23+
| 019 | [Remove Nth Node From End of List](https://github.com/yanglbme/leetcode/tree/master/solution/019.Remove%20Nth%20Node%20From%20End%20of%20List) | `Linked List`, `Two Pointers` |
2324

2425
### Hard
2526

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
## 删除链表的倒数第N个节点
2+
### 题目描述
3+
4+
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
5+
6+
示例:
7+
```
8+
给定一个链表: 1->2->3->4->5, 和 n = 2.
9+
10+
当删除了倒数第二个节点后,链表变为 1->2->3->5.
11+
```
12+
说明:
13+
14+
给定的 n 保证是有效的。
15+
16+
进阶:
17+
18+
你能尝试使用一趟扫描实现吗?
19+
20+
### 解法
21+
快指针 fast 先走 n 步,接着快指针 fast 与慢指针 slow 同时前进,等到快指针指向链表最后一个结点时,停止前进。然后将 slow 的 next 指向 slow.next.next,即删除了第 n 个结点。最后返回头指针。
22+
23+
这里设置了 pre 虚拟结点(指向 head )是为了方便处理只有一个结点的情况。
24+
25+
```java
26+
/**
27+
* Definition for singly-linked list.
28+
* public class ListNode {
29+
* int val;
30+
* ListNode next;
31+
* ListNode(int x) { val = x; }
32+
* }
33+
*/
34+
class Solution {
35+
public ListNode removeNthFromEnd(ListNode head, int n) {
36+
ListNode pre = new ListNode(-1);
37+
pre.next = head;
38+
ListNode fast = pre;
39+
ListNode slow = pre;
40+
41+
// 快指针先走 n 步
42+
for (int i = 0; i < n; ++i) {
43+
fast = fast.next;
44+
}
45+
while (fast.next != null) {
46+
fast = fast.next;
47+
slow = slow.next;
48+
}
49+
50+
slow.next = slow.next.next;
51+
return pre.next;
52+
}
53+
}
54+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Solution {
2+
public ListNode removeNthFromEnd(ListNode head, int n) {
3+
ListNode pre = new ListNode(-1);
4+
pre.next = head;
5+
ListNode fast = pre;
6+
ListNode slow = pre;
7+
8+
// 快指针先走 n 步
9+
for (int i = 0; i < n; ++i) {
10+
fast = fast.next;
11+
}
12+
while (fast.next != null) {
13+
fast = fast.next;
14+
slow = slow.next;
15+
}
16+
17+
slow.next = slow.next.next;
18+
return pre.next;
19+
}
20+
}

0 commit comments

Comments
 (0)