一问题描述
1.给你一个链表的头节点 head ,判断链表中是否有环。
2.返回入环的第一个节点
二.示例代码
public class CircleNode {
public static void main(String[] args) {
ListNode listNode = new ListNode(1);
ListNode listNode2 = new ListNode(2);
ListNode listNode3 = new ListNode(3);
ListNode listNode4 = new ListNode(4);
listNode.next = listNode2;
listNode2.next = listNode3;
listNode3.next = listNode4;
listNode4.next = listNode2;
boolean result = circleNode(listNode);
System.out.println(result);
ListNode result2 = circleNode2(listNode);
System.out.println(result2);
}
private static boolean circleNode(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
return true;
}
}
return false;
}
private static ListNode circleNode2(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
fast = head;
while (fast != slow) {
fast = fast.next;
slow = slow.next;
return fast;
}
}
}
return null;
}
}