要是链表节点个数为奇数时刚好指向中间点;为偶数时指向中间两个的第一个元素。
private static ListNode findMiddle(ListNode head) {
ListNode slow = head, fast = head.next;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
要是链表节点个数为奇数时刚好指向中间点;为偶数时指向中间两个的第二个元素。
private static ListNode findMiddle(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}