LeetCode--No.141--Linked List Cycle

来源:互联网 发布:tps跨境电商是网络传销 编辑:程序博客网 时间:2024/06/05 06:28

Given a linked list, determine if it has a cycle in it.

Follow up:

Can you solve it without using extra space?

以下是正确的解法

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


**************************************************************************************************************

以下是错误解法:

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

这个错误实在太幼稚=。=记下来以免再犯。将判断条件写在while中,一开始slow与fast就是相等的。所以不会执行while,直接返回true。



0 0