
利用快慢指针
快指针一次走两个,慢指针一次走一个。当快指针走到头,慢指针的位置就是中间节点

class Solution {
public ListNode middleNode(ListNode head) {
ListNode fast=head;
ListNode slow=head;
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
}
return slow;
}
}
网友评论