现在的位置: 首页 > 综合 > 正文

LeetCode – Linked List Cycle

2019年04月17日 ⁄ 综合 ⁄ 共 706字 ⁄ 字号 评论关闭

http://oj.leetcode.com/problems/linked-list-cycle/

  A very classical interview question. The challenge exists in "without using extra space".

  So we use two pointers to go over the linked-list, one is faster, one is slower. If there is no circle, they will run into null, otherwise they will meet each other
eventually since they move around in the cycle and the faster pointer always move one step further than the slower one.

/**
 * 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) {
        
    	ListNode fast = head;
    	ListNode slow = head;
    	
    	
    	while(fast != null && slow !=null)
    	{
    		fast = fast.next;
    		if(fast == null)
    			return false;
    		fast = fast.next;
    		
    		slow = slow.next;
    		
    		if(fast == slow)
    			return true;
    	}
    	
    	return false;
    }
}

抱歉!评论已关闭.