题目描述
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
code: /** * 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 snode = head; ListNode fnode = head; while(fnode != null && fnode.next != null) { fnode = fnode.next.next; snode = snode.next; if(snode == fnode) return true; } return false; } }
use a fast node and a slow node, if the fast node can match the slow node, then it can be concluded that it has a cycle.