[Microsoft] Linked List Cycle

来源:互联网 发布:蓝牙怎么传软件 编辑:程序博客网 时间:2024/06/06 08:52
/** * Definition for ListNode. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int val) { *         this.val = val; *         this.next = null; *     } * } */ public class Solution {    /**     * @param head: The first node of linked list.     * @return: True if it has a cycle, or false     */    public boolean hasCycle(ListNode head) {          if(head==null){            return false;        }                ListNode fast=head;        ListNode slow=head;        while(fast.next!=null && fast.next.next!=null){        //只有保证fast.next不为空,才能有fast.next.next            slow=slow.next;            fast=fast.next.next;            if(slow==fast){                                    //最终slow追上fast                return true;            }        }        return false;    }   }

原创粉丝点击