标签:
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:
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:
代码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 }
扩展:计算环形链表的长度可参考思路二,快慢相差一个链表的长度,相减即可获得长度。
LeetCode 141. Linked List Cycle
标签:
原文地址:http://www.cnblogs.com/angryorange/p/5908600.html