1. 输入链表头节点,奇数长度返回中点,偶数长度返回上中点
public static ListNode findTopCenter(ListNode root) {
if (root == null) {
return null;
}
ListNode slow = root,fast = root;
while (fast != null && fast.getNext() != null && fast.getNext().getNext() != null) {
slow = slow.getNext();
fast = fast.getNext().getNext();
}
return slow;
}
2.输入链表头节点,奇数长度返回中点,偶数长度返回下中点
public static ListNode findDownCenter(ListNode root) {
if (root == null) {
return null;
}
ListNode slow = root,fast = root;
while (fast != null && fast.getNext() != null) {
slow = slow.getNext();
fast = fast.getNext().getNext();
}
return slow;
}
3.输入链表头节点,奇数长度返回中点前一个,偶数长度返回上中点前一个
public static ListNode findPreTopCenter(ListNode root) {
if (root == null) {
return null;
}
ListNode slow = root,fast = root, pre = null;
while (fast != null && fast.getNext() != null && fast.getNext().getNext() != null) {
pre = slow;
slow = slow.getNext();
fast = fast.getNext().getNext();
}
return pre;
}
4.输入链表头节点,奇数长度返回中点前一个,偶数长度返回下中点前一个
public static ListNode findPreDownCenter(ListNode root) {
if (root == null) {
return null;
}
ListNode slow = root,fast = root, pre = null;
while (fast != null && fast.getNext() != null) {
pre = slow;
slow = slow.getNext();
fast = fast.getNext().getNext();
}
return pre;
}