项目github地址:bitcarmanlee easy-algorithm-interview-and-practice
欢迎大家star,留言,一起学习进步
Given a linked list, determine if it has a cycle in it.
原题是判断一个链表是否有环。我们给加大难度,找出环的起点。
判断链表是否有环比较简单。设置两个快慢指针,分别从链表的头节点出发,慢指针每次向后移动一步,快指针移动两步。如果链表存在环,快慢指针一定会在环里相遇。
求环入口位置具体逻辑见代码。
public class LinkedListCycle {
public static Node init_linkedlist() {
Node head = new Node(0);
Node node1 = new Node(1);
Node node2 = new Node(2);
Node node3 = new Node(3);
head.next = node1;
node1.next = node2;
node2.next = node3;
node3.next = node1;
return head;
}
public static Node hasCycle(Node head) {
Node slow = head;
Node fast = head;
//如果相遇,说明有环
while(slow != null && fast != null) {
slow = slow.next;
fast = fast.next.next;
if(slow == fast) {
System.out.println("There is a cycle!");
break;
}
}
//找环的入口
slow = head;
while(slow != fast) {
slow = slow.next;
fast = fast.next;
}
return fast;
}
public static void main(String[] args) {
Node head = init_linkedlist();
Node cycle_first = hasCycle(head);
System.out.println(cycle_first.val);
}
}
class Node {
int val;
Node next;
public Node(int val) {
this.val = val;
this.next = null;
}
}