一、加虚拟节点
1、找到中间节点的上一个节点
1 2 3 4 5 6 7 8 null
| |
slow fast
1 2 3 4 5 6 7 null
| |
slow fast
ListNode dummy = new ListNode();
dummy = head;
ListNode slow = dummy,fast = dummy;
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
2、在偶数个时找到的是后一半的第一个
1 2 3 4 5 6 7 8 null
| |
slow fast
1 2 3 4 5 6 7 null
| |
slow fast
ListNode dummy = new ListNode();
dummy = head;
ListNode slow = dummy,fast = dummy;
while(fast != null){
slow = slow.next;
fast = fast.next;
if(fast != null) fast = fast.next;
}
二、不加虚拟节点
1、找到中间节点的下一个节点
适合归并排序时用
1 2 3 4 5 6 7 8 null
| |
slow fast
1 2 3 4 5 6 7 null
| |
slow fast
ListNode slow = head,fast = head;
while(fast != null){
slow = slow.next;
fast = fast.next;
if(fast != null) fast = fast.next;
}
2、在偶数时找到前一半的最后一个
1 2 3 4 5 6 7 8 null
| |
slow fast
1 2 3 4 5 6 7 null
| |
slow fast
ListNode slow = head,fast = head;
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}