Linked List Cycle

来源:互联网 发布:qq飞车幻灵奇迹数据 编辑:程序博客网 时间:2024/06/16 09:55
/** * 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;        while(fast.next != null && fast.next.next != null){            slow = slow.next;            fast = fast.next.next;            if (fast.val == slow.val){                return true;            }        }        return false;    }}
0 0