首页 > 其他 > 详细

Linked list cycle

时间:2014-11-20 13:27:55      阅读:287      评论:0      收藏:0      [点我收藏+]

Given a linked list, determine if it has a cycle in it. (Without using eatra space)

//Solution: define two pointers, one moves one step each time while the other moves two steps. If the second one catches the first at some point, return true.

Java:

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

 

 

Python:

# Definition for singly-linked list. 
# class ListNode: 
#     def __init__(self, x): 
#         self.val = x 
#         self.next = None 
 
class Solution: 
    # @param head, a ListNode 
    # @return a boolean 
    def hasCycle(self, head): 
        if head==None: 
            return False 
        first = head 
        second = head 
        while first.next!=None and second.next!=None and second.next.next!=None: 
            first = first.next 
            second = second.next.next 
            if first==second: 
                return True 
        return False

Linked list cycle

原文:http://www.cnblogs.com/cs-jack-cheng/p/4110349.html

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