1 題目描述
給定一個帶有頭結點 head 的非空單鏈表,返回鏈表的中間結點。
如果有兩個中間結點,則返回第二個中間結點。
示例 1:
輸入:[1,2,3,4,5]
輸出:此列表中的結點 3 (序列化形式:[3,4,5])
返回的結點值爲 3 。 (測評系統對該結點序列化表述是 [3,4,5])。
注意,我們返回了一個 ListNode 類型的對象 ans,這樣:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, 以及 ans.next.next.next = NULL.
示例 2:
輸入:[1,2,3,4,5,6]
輸出:此列表中的結點 4 (序列化形式:[4,5,6])
由於該列表有兩個中間結點,值分別爲 3 和 4,我們返回第二個結點。
提示:
給定鏈表的結點數介於 1 和 100 之間。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/middle-of-the-linked-list
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
2 解題思路
按順序將每個結點放入數組 A 中。然後中間結點就是 A[A.Length/2],因爲我們可以通過索引檢索每個結點。
3 解決代碼
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode middleNode(ListNode head) {
ListNode[] A = new ListNode[100];
int t = 0;
while(head != null){
A[t++] = head;
head = head.next;
}
return A[t/2];
}
}