标签:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Solution1:
思路:有cycle:1.循环退不出来2.有个节点被指两次。分析清楚了就很简单,用hashset记录每个节点,如果碰到重复节点就是cycle,没有节点就会最终退出循环。
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public boolean hasCycle(ListNode head) { Set<ListNode> res=new HashSet<ListNode>(); if(head==null) { return false; } ListNode slow=head; while(slow!=null) { if(!res.contains(slow)) { res.add(slow); } else { return true; } slow=slow.next; } return false; } }
Solution2:
dicussion中O(1)解法:快慢指针。如果有cycle,那么快慢指针肯定会相遇,如果没有cycle最终快慢指针不同。
public class Solution { public boolean hasCycle(ListNode head) { if(head == null || head.next == null) return false; ListNode slow = head; ListNode fast = head.next; while(fast != null && fast != slow && fast.next != null){ slow = slow.next; fast = fast.next.next; } if(fast == slow) return true; return false; } }
标签:
原文地址:http://www.cnblogs.com/Machelsky/p/5863421.html