2026-01-01 16:37:21
答案:使用快慢指针法可以高效地找到链表的中点,时间复杂度为O(n/2)。
方法思路:
解决代码:
/ * Definition for ListNode * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { / * @param head: the head of linked list. * @return: a middle node of the linked list */ public ListNode middleNode(ListNode head) { if (head == null || head.next == null) { return head; } ListNode slow = head, fast = head.next; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } return slow; }}代码解释:
这种方法确保了在O(n/2)的时间复杂度内找到中点,且只需遍历链表一次,高效且简洁。