leetcode总结2

Linked List Cycle

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

题目分析:要判断一个链表里面有没有环。首先我们可以思考下如果这里面有环,那么会有以下2中情况:该链表是循环链表和该链表的末尾有一个环。那么,我们可以采用2个指针的方法,一个步长比另一个的指针步长要大,那么如果没有环,当快指针指到最后一个节点的时候,我们可以判断该链表没有环;如果该链表有环,那么总会有某一次两个指针指向同一个节点。

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 || head.next == null)
            return false;
        
        ListNode slow = head;
        ListNode fast = head.next;
        while(slow != fast){
            if(fast == null || fast.next == null){
                return false;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        return true;
        
    }
}
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if head == None or head.next == None:
            return False
        fast = head.next
        slow = head
        while fast != slow:
            if fast == None or fast.next == None:
                return False
            fast = fast.next.next
            slow = slow.next
            
        return True


你可能感兴趣的:(leetCodes刷题总结)