环形链表 II

题目描述:给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。

为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意,pos 仅仅是用于标识环的情况,并不会作为参数传递到函数中。

说明:不允许修改给定的链表。

进阶:

你是否可以使用 O(1) 空间解决此题?

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle-ii/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:哈希表

HashSet判断节点是否重复。

解法二:双指针法

使用快慢节点,如果有环,则这两个节点必回相遇。

  1. import java.util.HashSet;
  2. import java.util.Set;
  3. public class LeetCode_142 {
  4. /**
  5. * 哈希
  6. *
  7. * @param head
  8. * @return
  9. */
  10. public static ListNode detectCycle(ListNode head) {
  11. if (head == null) {
  12. return null;
  13. }
  14. Set<ListNode> nodes = new HashSet<>();
  15. nodes.add(head);
  16. while (head.next != null) {
  17. // 如果next节点在哈希表中出现过,说明成环了, 而且next节点肯定是入环点,直接返回
  18. if (nodes.contains(head.next)) {
  19. return head.next;
  20. }
  21. nodes.add(head.next);
  22. head = head.next;
  23. }
  24. return null;
  25. }
  26. /**
  27. * 双指针法
  28. *
  29. * @param head
  30. * @return
  31. */
  32. public static ListNode detectCycle2(ListNode head) {
  33. if (head == null) {
  34. return null;
  35. }
  36. ListNode slow = head, fast = head;
  37. while (fast != null) {
  38. slow = slow.next;
  39. if (fast.next != null) {
  40. fast = fast.next.next;
  41. } else {
  42. return null;
  43. }
  44. if (fast == slow) {
  45. ListNode ptr = head;
  46. while (ptr != slow) {
  47. ptr = ptr.next;
  48. slow = slow.next;
  49. }
  50. return ptr;
  51. }
  52. }
  53. return null;
  54. }
  55. public static void main(String[] args) {
  56. ListNode head = new ListNode(3);
  57. head.next = new ListNode(2);
  58. head.next.next = new ListNode(0);
  59. head.next.next.next = new ListNode(-4);
  60. head.next.next.next.next = head.next;
  61. System.out.println(detectCycle(head) == null ? -1 : detectCycle(head).val);
  62. System.out.println(detectCycle2(head) == null ? -1 : detectCycle2(head).val);
  63. }
  64. }

【每日寄语】 人世间不可预料的事情太多了,但是不管怎样,社会还会照样运行。一个人不管有多大的成就,在世界万物中都是非常渺小的,所以要珍惜每一分每一秒。