Linked List Cycle
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
思路:模拟两个人沿着固定路线跑步,看先跑的人是否可以追上后跑的人
java代码:
- 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(fast==null) return false;
- if(fast==slow) return true;
- }
- return false;
- }