public class MiddleNode { public static void main(String[] args) { ListNode head = new ListNode(1); head.next = new ListNode(2); head.next.next = new ListNode(3); head.next.next.next = new ListNode(4); System.out.println(middleNode(head).val); }
public static ListNode middleNode(ListNode head) { //快慢指针 ListNode slow = head; ListNode fast = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } return slow; } }
//Definition for singly-linked list. class ListNode { int val; ListNode next;