問題
給出任意單向鏈表,找出並返回該鏈表的中間節點。
奇數長度的鏈表,例如:1->2->3->4->5
返回節點 3
偶長度的鏈表,例如:1->2->3->4->5->6
返回節點 4
解題思路
與鏈表中環的檢測一樣,這題同樣可以使用快慢指針來解決。
定義兩個指針fast和slow。slow一次遍歷一個節點,fast一次遍歷兩個節點,由於fast的速度是slow的兩倍,所以當fast遍歷完鏈表時,slow所處的節點就是鏈表的中間節點。
代碼
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
/**
* 尋找鏈表的中間節點
*
* @param node
* @return
*/
public static ListNode middleNode(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode slow = head;
ListNode fast = head.next;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return fast == null ? slow : slow.next;
}
博文地址
https://www.taowong.com/blog/2018/10/20/data-strutctures-and-algorithm-05.html