Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Can you solve it without using extra space?
Solution:
复杂度O(n)的方法,使用两个指针slow,fast。两个指针都从表头开始走,slow每次走一步,fast每次走两步,如果fast遇到null,则说明没有环,返回false;如果slow==fast,说明有环,并且此时fast超了slow一圈,返回true。
two pointers, one traverses twice as fast as the other, return true if they meet
/** * 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) { if(head == null) return false; ListNode slow = head; ListNode fast = head.next; //check head first. If head==null, no head.next exists boolean isMeeting = false; while(fast != null) { if(fast == slow) { isMeeting = true; break; } fast = fast.next; if(fast != null) { slow = slow.next; fast = fast.next; } } return isMeeting; } }
No comments:
Post a Comment