Leetcode Linked List Cycle II
2016-12-29 04:22
393 查看
题意:判断链表中是否右环, 如果有则输出环的起始点, 如果没有则输出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)还需思考。
思路:记录链表的地址,用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)还需思考。
相关文章推荐
- LeetCode:Linked List Cycle II
- LeetCode:Linked List Cycle II
- LeetCode | Linked List Cycle II
- LeetCode | Linked List Cycle II
- LeetCode之Linked List Cycle II
- leetcode - Linked List Cycle II
- [Leetcode 141 & 142, medium] Linked List Cycle (I and II)
- [LeetCode] - Linked List Cycle II
- [leetcode]Linked List Cycle II
- LeetCode: Linked List Cycle II
- [算法][LeetCode]Linked List Cycle & Linked List Cycle II——单链表中的环
- [LeetCode] Linked List Cycle II
- Leetcode: Linked List Cycle II
- [LeetCode]Linked List Cycle II
- [leetcode]Linked List Cycle II
- Leetcode Linked List Cycle II
- leetcode: Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode - Linked List Cycle II
- leetcode Linked List Cycle II