快慢指针
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode middleNode(ListNode head) {
//快指针
ListNode fast = head;
//慢指针
ListNode slow = head;
//快指针每次走两步,慢指针每次走一步。当链表节点数为奇数时,fast.next==null;当链表节点数为偶数时,fast==null。
while(fast!=null&&fast.next!=null){
fast = fast.next.next;
slow = slow.next;
}
//返回从中间节点开始的序列化链表
return slow;
}
}
