給定一個帶有頭結點 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
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
這道題有點簡單,最開始的想法,先遍歷找長度,然後再遍歷到中間
/**
* 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 temp = head;
int count = 0;
while(temp!= null){
temp = temp.next;
count++;
}
temp = head;
for(int i = 0; i < count/2; i++){
temp = temp.next;
}
return temp;
}
}
高級做法,雙指針
/**
* 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 fast = head;
ListNode low = head;
while(fast != null && fast.next != null && fast.next != null){
fast = fast.next.next;
low = low.next;
}
return low;
}
}