leetcode经典例题第九题,求证一个链表是否有环。
题目描述
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
解题思路
环的长度就是快指针比慢指针多走的长度,因此快慢指针如果能相遇,那么表明有环,否则就表示没有环。
代码提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public class Solution { public boolean hasCycle(ListNode head) { if(head == null || head.next == null){ return false; } ListNode slow = head; ListNode fast = head; while(fast != null && fast.next != null){ slow = slow.next; fast = fast.next.next; if(slow == fast){ return true; } } return false; } }
|