Linked List Cycle

来源:互联网 发布:cnrds 数据产品 编辑:程序博客网 时间:2024/06/08 14:27

使用两个指针,一个faster一次走两步,一个slower一次走一步,若有环路则faster与slower必能相遇

class ListNode {    int val;    ListNode next;    ListNode(int x) {        val = x;        next = null;    }}public class Solution {    public boolean hasCycle(ListNode head) {        ListNode faster = head;        ListNode slower = head;        while(faster != null && faster.next != null){            faster = faster.next.next;            slower = slower.next;            if(faster == slower)                return true;        }        return false;    }}
0 0