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;
    }
   }

猜你喜欢

转载自blog.csdn.net/qq_38210187/article/details/83350521