Linked List Cycle

来源:互联网 发布:2016年汽车销售数据 编辑:程序博客网 时间:2024/06/05 15:48

c++

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    bool hasCycle(ListNode *head) {        if (head == nullptr || head->next == nullptr)            return false;        unordered_set<ListNode *> cache;        while (head != nullptr) {            if (cache.find(head) != cache.end())                return true;            cache.insert(head);            head = head->next;        }        return false;    }};

python

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def hasCycle(self, head):        """        :type head: ListNode        :rtype: bool        """        if not head or not head.next:            return False        fast = slow = head        while slow and fast and fast.next:            fast = fast.next.next            slow = slow.next            if(fast == slow):                return True        return False

reference:
https://leetcode.com/discuss/106782/in-place-python-code-beats-90%25

0 0