首页 > 其他 > 详细

Linked List Cycle

时间:2014-02-18 12:46:37      阅读:292      评论:0      收藏:0      [点我收藏+]

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

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

两个指针,一个一次走两步,一个一次走一步,相遇说明有环

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

Linked List Cycle

原文:http://www.cnblogs.com/RazerLu/p/3553574.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!