找到数组的中点很容易
int findMid(int arr[]){
if(arr==null){
return -1;
}
return arr.length/2;
}
找到一条单链表的中点呢? 有没有好的想法? 是的就是用一快一慢的两个指针,快指针每次走两步,慢指针每次走一步,那么快指针到达链尾的时候,慢指针就走了中点,返回它就行了!
class ListNode{
int val;
ListNode next;
ListNode(int val){
this.val=val;
}
}
ListNode findMid(ListNode head){
if(head==null||head.next==null){
return head;
}
ListNode slow=head,fast=head.next;
while(fast!=null && fast.next!=null){
slow=slow.next; //一步
fast=fast.next.next; //两步
}
return slow;
}
一步两步似爪牙,似魔鬼的步伐。。。。。。