在leetcode中,环形链表1是判断链表是否存在环,环形链表2是判断环的连接点是哪一个。存在两种解法:
- 使用set进行存储,如果在遍历过程中,遇到set中有重复的,其实这两个问题都解决了,一个是判断出是否存在环,另一方面第一个重复的肯定就是连接点。
- 使用快慢指针。慢指针一次移动一个,快指针一次移动两个。如果在快指针不等于null前相遇说明存在环,否则说明出现null这个链表就不存在环。
环状链表1:
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
if(head == null || head.next ==null)
return false;
slow = slow.next;
fast = fast.next.next;
while(fast != null){
if(fast == slow){
return true;
}
if(fast.next != null){
fast = fast.next.next;
slow = slow.next;
}else{
return false;
}
}
return false;
}
}
环状链表2
/**
* 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 slow = head;
ListNode fast = head;
if(head == null || head.next ==null)
return null;
slow = slow.next;
fast = fast.next.next;
while(fast != null){
if(fast == slow){
break;
}
if(fast.next != null){
fast = fast.next.next;
slow = slow.next;
}else{
break;
}
}
if(slow != fast)
return null;
else{
ListNode p = head;
while(p != slow){
p = p.next;
slow = slow.next;
}
return p;
}
}
}