给定一个链表,判断链表中是否有环。如果有,返回true,没有,返回false。
Set标记:利用一个set记录每次便利的节点,因为set可以去重,所以利用set判断重复的元素,遍历到重复的元素,就可以返回true,若遍历完成,则说明没有重复的元素,返回false。时间复杂度和空间复杂度都是O(n)
双指针:利用一个快指针,一次遍历两个步距,另一个慢指针,一次遍历一个步距。如果有环,那么快指针肯定可以遍历到慢指针。如果没有环,那么快指针最先遍历结束,指向null。空间复杂度没了,时间复杂度不变。
上代码:
import java.util.HashSet;
import java.util.Set;
//11.环形链表
public class LinkCycle11 {
static class ListNode{
int val;
ListNode next;
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public static void main(String[] args) {
ListNode node5 = new ListNode(5,null);
ListNode node4 = new ListNode(4,node5);
ListNode node3 = new ListNode(3,node4);
ListNode node2 = new ListNode(2,node3);
ListNode node1 = new ListNode(1,node2);
node5.next=node3;
System.out.println(hasCycle(node1));
System.out.println(hasCycle2(node1));
}
//利用set记录,去重
public static boolean hasCycle(ListNode head){
Set<ListNode> set = new HashSet<>();
while (head!=null){
if (!set.add(head)){
return true;
}
head=head.next;
}
return false;
}
//双指针
public static boolean hasCycle2(ListNode head){
if (head==null||head.next==null){
return false;
}
ListNode slow=head;
ListNode quick = head.next;
while (slow!=quick){
if (quick==null||quick.next==null){
return false;
}
slow=slow.next;
quick=quick.next.next;
}
return true;
}
}
结果:
true
true