LeetCode (Linked List Cycle II)

来源:互联网 发布:淘宝贷款还不起怎么办 编辑:程序博客网 时间:2024/06/03 14:17

Problem:

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Solution:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *detectCycle(ListNode *head) {        unordered_map<ListNode*, int> map;        while(head && map.find(head) == map.end()){            map[head];            head = head->next;        }        return head;     }};


原创粉丝点击