您的位置:首页 > 其它

【LeetCode】Linked List Cycle II

2014-11-05 22:49 337 查看
题目地址:https://oj.leetcode.com/problems/linked-list-cycle-ii/

解题思路:快慢指针,相遇后快指针回到起点以每次一步走,再次相遇点为环的起点

注意【纯回环】,空链表,无环链表等各种情况

/**
* Definition for singly-linked list.
* class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head==null)return null;
ListNode fast=head;
ListNode low=head;
ListNode second=head;
boolean hasCycle=false;
while(fast!=null&&low!=null){
if(fast.next!=null)fast=fast.next.next;
else {
break;
}
low=low.next;
if(fast==low){
hasCycle=true;
break;
}
}
if(!hasCycle) return null;
else{
while(second!=low){
second=second.next;
low=low.next;
}
return low;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: