Given the head
of a singly linked list, return the middle node of the linked list.
If there are two middle nodes, return the second middle node.
Example 1:
Input: head = [1,2,3,4,5] Output: [3,4,5] Explanation: The middle node of the list is node 3.
Example 2:
Input: head = [1,2,3,4,5,6] Output: [4,5,6] Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.
Constraints:
- The number of nodes in the list is in the range
[1, 100]
. 1 <= Node.val <= 100
显然快慢指针,但是被循环终止条件卡住了……呃……只要fast和fast.next都不为null就可以移fast和slow了。但是,注意注意注意!这里题目给的条件是,如果是偶数个数的话,返回的是第二部分的第一个,而不是第一部分的最后一个,于是用的是fast != null && fast.next != null,这样就会更多地move slow。如果要求第一部分的最后一个,需要把条件改成fast.next != null && fast.next.next != null。(做234的时候才发现……)
/**
* 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;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
}