141. Linked List Cycle 没做出来 看的别人的答案 很巧妙

来源:互联网 发布:qq一键加好友软件 编辑:程序博客网 时间:2024/05/19 20:23

有linkedlist的相关知识 可以参考:http://blog.csdn.net/jdsjlzx/article/details/41654295

判断list里面有没有回路:

没做出来 网上有个很nb的做法:'fast' travel two steps per time while 'slow' travel one step per time, if there is a cycle, 'fast' will meet 'slow'.

fast比slow快两步 如果有circle 则一定会有fast=slow的时候

代码如下:

public class Solution {    public boolean hasCycle(ListNode head) {        if(head == null || head.next == null) return false;        ListNode slow = head;        ListNode fast = head.next;        while(fast != null && fast != slow && fast.next != null){            slow = slow.next;            fast = fast.next.next;        }        if(fast == slow) return true;        return false;    }}
O(1)空间复杂度 O(n)的时间复杂度

0 0