1. 程式人生 > >Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using e

Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using e

        不得不說在leetcode上面刷題真的收穫很大,一些在學校老師根本不會教給你的知識點在這裡可以學到。

然後這題其實自己只是想到遍歷元素然後就是判斷是不是又重新遍歷到頭節點而已,但效率太低。無奈找了提示,看了別人的程式碼就心領神會了。

public class Solution {     public boolean hasCycle(ListNode head) {           ListNode slow = head, fast = head;         while (fast != null && fast.next != null) {             slow = slow.next;             fast = fast.next.next;             if (slow == fast)                  return true;         }         return false;     }    }