您的位置:首页 > 其它

LeetCode | Linked List Cycle

2014-12-04 20:45 316 查看
Given a linked list, determine if it has a cycle in it.

Follow up: Can you solve it without using extra space?

tags提示:two pointers

采用“快慢双指针”的方法来判断:

每次slow_pointer前进一格,而fast_pointer前进两格,如若list存在cycle的话,则快指针一定会与慢指针重合。(因为当list存在cycle时,向后遍历是一个无限循环的过程,在此循环中两指针一定会重合)

public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null || head.next==null) return false;

ListNode slow_pointer = head;
ListNode fast_pointer = head;

while(fast_pointer!=null && fast_pointer.next!=null){ //向后遍历中出现null,则一定无cycle
slow_pointer = slow_pointer.next;
fast_pointer = fast_pointer.next.next;

if(slow_pointer == fast_pointer){ //如果快指针与慢指针重合了,则一定有cycle
return true;
}
}

return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode list cycle