使用双指针,一快一慢指针进行遍历链表,例如:1,2,3,4,5,返回3。1,2,3,4,5,6,返回4,代码如下
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
class Solution {
public static ListNode middleNode(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode slow = head;
ListNode fast = head.next;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
//链表长度为偶数时,返回慢指针的后继节点
return fast == null ? slow : slow.next;
}
}