题目:
思路:
判断链表成环,可以使用快慢指针,如果指针先遍历到null,则不成环,若二者相重叠,则成环,判断入环点有两个方法,1在重叠时,新加一个从head开始的结点,和重叠点一起next,下一个重叠点为入环点,2是用hash把快指针到过的地方进行标记。
代码:
哈希+快慢指针:
/**
* 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) {
HashMap<ListNode,Integer> hash=new HashMap<ListNode,Integer>();
ListNode l1=head;
ListNode l2=head;
while(l2!=null){
if(hash.containsKey(l2)){
return l2;
}else{
hash.put(l2,0);
}
l1=l1.next;
l2=l2.next;
if(l2==null){
return null;
}else{
if(hash.containsKey(l2)){
return l2;
}else{
hash.put(l2,0);
}
l2=l2.next;
}
}
return null;
}
}
三个指针
/**
* 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) {
ListNode l1=head;
ListNode l2=head;
while(l2!=null){
l1=l1.next;
l2=l2.next;
if(l2==null){
return null;
}else{
l2=l2.next;
if(l2==l1){
ListNode l3=head;
while(l3!=l1){
l1=l1.next;
l3=l3.next;
}
return l3;
}
}
}
return null;
}
}