样例
链表 1->2->3
的中点是 2
。
链表 1->2
的中点是 1
。
算法思路
使用快慢指针实现,慢指针一次移动一个节点,快节点一次移动两个节点,快指针到达终点时,慢指针指向中点
代码实现(JAVA)
public ListNode middleNode(ListNode head) {
// write your code here
if(head == null)
return null;
ListNode slow = head;
ListNode fast = head;
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
return slow;
}