LeetCode 循环链表判断

来源:互联网 发布:手机淘宝历史版本5.1.1 编辑:程序博客网 时间:2024/05/16 15:17

判断一个单链表是否循环.

解题思想,龟兔赛跑原理,如果有循环的话,乌龟和兔子总会相遇(小学数学书中的龟兔相遇问题)。


Java version

/** * 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 oneStep = head;        ListNode twoStep = head;        while(oneStep !=null && twoStep !=null && twoStep.next != null){            oneStep = oneStep.next;            twoStep = twoStep.next.next;            if(oneStep == twoStep) return true;        }        return false;    }}


0 0
原创粉丝点击