之前刷剑指offer遇到寻找链表环的入口节点,需要使用到快慢指针,然后题一变,发现自己总是不能立马联想起来。总结一下快慢指针法在链表中的一些常见的用处。
一、快慢指针判断单链表是否有环
leetcode 141 https://leetcode.com/problems/linked-list-cycle/submissions/
快指针每次走2步,慢指针每次走1步,如果链表中有环,则两个指针就会相遇。
public boolean hasCycle(ListNode head) {
if(head==null) return false;
ListNode fast=head;
ListNode slow=head;
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
if(fast==slow){
return true;
}
}
return false;
}
二.寻找链表环的入口节点
在上面的基础上,如果判断出链表中存在环,我们只需要将其中一个指针slow重新指向链表的头,另外一个指针fast在相遇处不动,此时重新开始走,两个指针每次都各走一步,再次相遇的节点就是环的入口节点。
public ListNode detectCycle(ListNode head) {
if(head==null) return null;
ListNode fast=head;
ListNode slow=head;
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
if(fast==slow){
break;
}
}
if(fast==null||fast.next==null) return null;
slow=head;
while(fast!=slow){
fast=fast.next;
slow=slow.next;
}
return slow;
}
三、求有序链表的中位数
快指针每次走2步,慢指针每次走1步,当快指针走到链表末尾时,慢指针刚好到链表中间
//求有序链表的中位数
public double fun(ListNode head){
if(head==null) return -1.0;
ListNode fast=head;
ListNode slow=head;
while(fast.next!=null&&fast.next.next!=null){
slow=slow.next;
fast=fast.next.next;
}
if(fast.next!=null){
return slow.val/1.0;//说明有奇数个节点,此时slow正好是中位数
}else{
return (slow.val+slow.next.val)/2.0;//偶数个节点
}
}