LeetCode 141. Linked List Cycle

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

 1 /**
 2  * Definition for singly-linked list.
 3  */
 4 class ListNode {
 5     int val;
 6     ListNode next;
 7 
 8     ListNode(int x) {
 9         val = x;
10         next = null;
11     }
12 }

思路1:

  1. 遍历链表把所有的节点放入set中
    1. 若set中包含当前节点,则含有环
    2. 若set中没有,则把节点放入set
    3. 取下一个节点
  2. 若节点为null,则遍历结束,肯定没有环。

代码1:

 1   public boolean hasCycleBySet(ListNode head) {
 2         Set<ListNode> set = new HashSet<>();
 3         while(head != null){
 4             if(set.contains(head))
 5                 return true;
 6             else
 7                 set.add(head);
 8             head = head.next;
 9         }
10         return false;
11     }

思路2:

  1. 遍历链表,一次快(每次获取后面第二个),一次慢(每次获取后面第一个)
  2. 若快的节点为null或下一个为null,则不包含环
  3. 在若干次之后,若快的节点与慢的节点相同则包含环。(此时快的遍历比慢的遍历领先了一个链表的长度)

代码2:

 1   public boolean hasCycle(ListNode head) {
 2         if (head == null || head.next == null) {
 3             return false;
 4         }
 5         ListNode slow = head;
 6         ListNode fast = head.next;
 7         while (slow != fast) {
 8             if (fast == null || fast.next == null) {
 9                 return false;
10             }
11             slow = slow.next;
12             fast = fast.next.next;
13         }
14         return true;
15     }

扩展:计算环形链表的长度可参考思路二,快慢相差一个链表的长度,相减即可获得长度。

 1 public static boolean hasCycle(ListNode head) {
 2         if (head == null || head.next == null) {
 3             return false;
 4         }
 5         ListNode slow = head;
 6         ListNode fast = head.next;
 7         int f = 1;//上面两行赋值已前进了一次
 8         while (slow != fast) {
 9             if (fast == null || fast.next == null) {
10                 return false;
11             }
12             slow = slow.next;
13             fast = fast.next.next;
14             f++;
15         }
16         System.out.println("LinkedList.size:"+f);
17         return true;
18     }

 

posted @ 2016-09-26 11:48  账号早已注销  阅读(1111)  评论(0编辑  收藏  举报