142. 环形链表 II - 力扣(Leetcode)
这个逻辑过程还是很有趣的,有点数学在里面。
不过是初中水平。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| public class LinkedListCycleII142 { public static void main(String[] args){ ListNode head = initLinkedList(new int[]{1,2,3,4}); ListNode res = new Solution().detectCycle(head); System.out.println(res == null ? "null" : res.val); }
public static ListNode initLinkedList(int[] nums){ ListNode head = new ListNode(nums[0]); ListNode cur = head,node; for(int i = 1; i < nums.length; i++){ node = new ListNode(nums[i]); cur.next = node; cur = node; } return head; }
}
class ListNode { int val; ListNode next; public ListNode (){} public ListNode (int val){ this.val = val; } public ListNode (int val, ListNode next){ this.val = val; this.next = next; } }
class Solution { public ListNode detectCycle(ListNode head) { ListNode fast = head; ListNode slow = head;
while(fast != null && fast.next != null){ fast = fast.next.next; slow = slow.next; if (fast == slow) { slow = head; while(slow != fast){ slow = slow.next; fast = fast.next; } return slow; } } return null; } }
|