876. 链表的中间结点

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. class Solution {
  10. public ListNode middleNode(ListNode head) {
  11. if (head == null)
  12. return null;
  13. ListNode fast = head, slow = head;
  14. while (fast != null && fast.next != null) {
  15. slow = slow.next;
  16. fast = fast.next.next;
  17. }
  18. return slow;
  19. }
  20. }