876. 链表的中间结点
1.双指针 second 比 first 快一倍
2.若整个链表为奇数,在 first = first.next 之前判断 second.next == null,则包含中间的指针
代码:
class Solution {
public ListNode middleNode(ListNode head) {
if (head == null) {
return null;
}
ListNode prev = new ListNode(0);
prev.next = head;
ListNode first = head;
ListNode second = head;
while (second != null ) {
if (second.next == null) {
return first;
}
first = first.next;
second = second.next.next;
}
return first;
}
}