Skip to content

Commit 37f5fc6

Browse files
committed
Add solution 876
1 parent a597381 commit 37f5fc6

File tree

4 files changed

+78
-0
lines changed

4 files changed

+78
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ Complete solutions to Leetcode problems, updated daily.
1818
| 083 | [Remove Duplicates from Sorted List](https://github.com/yanglbme/leetcode/tree/master/solution/083.Remove%20Duplicates%20from%20Sorted%20List) | `Linked List` |
1919
| 203 | [Remove Linked List Elements](https://github.com/yanglbme/leetcode/tree/master/solution/203.Remove%20Linked%20List%20Elements) | `Linked List` |
2020
| 237 | [Delete Node in a Linked List](https://github.com/yanglbme/leetcode/tree/master/solution/237.Delete%20Node%20in%20a%20Linked%20List) | `Linked List` |
21+
| 876 | [Middle of the Linked List](https://github.com/yanglbme/leetcode/tree/master/solution/876.Middle%20of%20the%20Linked%20List) | `Linked List` |
2122

2223

2324
### Medium
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
## 链表的中间结点
2+
### 题目描述
3+
4+
给定一个带有头结点 head 的非空单链表,返回链表的中间结点。
5+
6+
如果有两个中间结点,则返回第二个中间结点。
7+
8+
9+
示例 1:
10+
```
11+
输入:[1,2,3,4,5]
12+
输出:此列表中的结点 3 (序列化形式:[3,4,5])
13+
返回的结点值为 3 。 (测评系统对该结点序列化表述是 [3,4,5])。
14+
注意,我们返回了一个 ListNode 类型的对象 ans,这样:
15+
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, 以及 ans.next.next.next = NULL.
16+
```
17+
18+
示例 2:
19+
```
20+
输入:[1,2,3,4,5,6]
21+
输出:此列表中的结点 4 (序列化形式:[4,5,6])
22+
由于该列表有两个中间结点,值分别为 3 和 4,我们返回第二个结点。
23+
```
24+
25+
提示:
26+
27+
- 给定链表的结点数介于 1 和 100 之间。
28+
29+
### 解法
30+
快指针 fast 和慢指针 slow 初始指向 head。循环开始,fast 每次走两步,slow 每次走一步,当快指针为 null 或者 快指针下一个结点为 null(简单抠一下边界可以了),退出循环。
31+
32+
```java
33+
/**
34+
* Definition for singly-linked list.
35+
* public class ListNode {
36+
* int val;
37+
* ListNode next;
38+
* ListNode(int x) { val = x; }
39+
* }
40+
*/
41+
class Solution {
42+
public ListNode middleNode(ListNode head) {
43+
if (head == null || head.next == null) {
44+
return head;
45+
}
46+
ListNode fast = head;
47+
ListNode slow = head;
48+
while (fast.next != null) {
49+
// 快指针每次循环走两步,慢指针走一步
50+
fast = fast.next.next;
51+
slow = slow.next;
52+
if (fast == null || fast.next == null) {
53+
return slow;
54+
}
55+
}
56+
return null;
57+
}
58+
}
59+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
public ListNode middleNode(ListNode head) {
3+
if (head == null || head.next == null) {
4+
return head;
5+
}
6+
ListNode fast = head;
7+
ListNode slow = head;
8+
while (fast.next != null) {
9+
// 快指针每次循环走两步,慢指针走一步
10+
fast = fast.next.next;
11+
slow = slow.next;
12+
if (fast == null || fast.next == null) {
13+
return slow;
14+
}
15+
}
16+
return null;
17+
}
18+
}

solution/876.Middle of the Linked List/Solution.py

Whitespace-only changes.

0 commit comments

Comments
 (0)