Linked List Cycle

来源:互联网 发布:超级优化女主角有谁 编辑:程序博客网 时间:2024/06/11 00:35
/** * 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 dummy = new ListNode(-1);        dummy.next = head;        ListNode fast = dummy;        ListNode slow = dummy;        while (fast.next != null && fast.next.next != null) {            fast = fast.next.next;            slow = slow.next;            if (slow == fast) {                return true;            }        }        return false;    }}

0 0