[LeetCode] 141. 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?

给定一个链表,判断是否有环存在。Follow up: 不使用额外空间。

解法:双指针,一个慢指针每次走1步,一个快指针每次走2步的,如果有环的话,两个指针肯定会相遇。

Java:

public class Solution {
    public boolean hasCycle(ListNode head) {
        ListNode slow = head, fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) return true;
        }
        return false;
    }
}

Python:

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):
        fast, slow = head, head
        while fast and fast.next:
            fast, slow = fast.next.next, slow.next
            if fast is slow:
                return True
        return False  

C++:

class Solution {
public:
    bool hasCycle(ListNode *head) {
        ListNode *slow = head, *fast = head;
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast) return true;
        }
        return false;
    }
};

  

类似题目:

[LeetCode] 142. Linked List Cycle II 链表中的环 II

 

All LeetCode Questions List 题目汇总

 

posted @ 2018-03-20 08:46  轻风舞动  阅读(241)  评论(0编辑  收藏  举报