我的代码:
验证链表环的时候,使用过快慢指针,这时候就是见证数学公式的能力了。
class Solution {
public ListNode middleNode(ListNode head) {
// 慢指针指向head内存地址
ListNode slow = head;
// 双判断head是否null
while(head != null) {
head = head.next;
// 只有head走第二步时候,slow才走
if(head != null) {
head = head.next;
slow = slow.next;
}
}
// 无论刚传入head是null或者head.next是null,都是正确的
return slow;
}
}
问题:
难度easy
链表环快慢指针问题:https://blog.csdn.net/qq_28033719/article/details/104853725
输入输出案例:
// 输入12345,返回3,3是中间节点
Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
// 输入123456,双数位时候,返回4,3和4都算是中间位,返回后面4
Input: [1,2,3,4,5,6]
Output: Node 4 from this list (Serialization: [4,5,6])