Leetcode Linked List Cycle II

来源:互联网 发布:双十一大学生网购数据 编辑:程序博客网 时间:2024/04/29 22:37

题意:判断链表中是否右环, 如果有则输出环的起始点, 如果没有则输出NULL。

思路:记录链表的地址,用hash表实现O(1)查找。

/** * 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) {        if(head == NULL) return head;                map<ListNode*, bool> ml;        ListNode* next = head;        while(next && !ml[next]) {            ml[next] = true;            next = next->next;        }                return next;    }};

如何实现空间的O(1)还需思考。

0 0
原创粉丝点击