LeetCode Note Java 00876:Middle of the Linked List

回傳輸入的 Linked List 的中間的 ListNode。

題目

Middle of the Linked List Easy

Given the head of a singly linked list, return the middle node of the linked list.

If there are two middle nodes, return the second middle node.

我的解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode middleNode(ListNode head) {
int count = 0;
ListNode tmp = head;
while (tmp != null) {
count++;
tmp = tmp.next;
}
int num = count / 2;
for (int i = 0; i < num; i++) {
head = head.next;
}
return head;
}
}

計算 head 總長後,算出中間是第幾個,再將 head 走到中間後回傳。

檢討

我的寫法總共走了 1.5 條 head,看到別人的只要走半條的步數就能回傳,覺得很厲害:

1
2
3
4
5
6
7
8
9
10
class Solution {
public ListNode middleNode(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}

補充:

經過 0014100142 的洗禮後,知道 slow 跟 fast 這種方法叫做龜兔賽跑。

參考資料

[Python/Java/C++] Simple Solution || One-Pass || Beginner Friendly || Detailed Explanation