Leetcode_linked-list-cycle-ii
来源:互联网 发布:mysql上一篇查询 编辑:程序博客网 时间:2024/05/16 13:05
地址:http://oj.leetcode.com/problems/linked-list-cycle-ii/
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Follow up:
Can you solve it without using extra space?
Follow up: 不使用额外空间代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { private: int Cnt_link_len(ListNode* head) { int cnt = 0; while(head) { ++cnt; head = head->next; } return cnt; } public: ListNode *detectCycle(ListNode *head) { if(!head) return NULL; ListNode *fast = head->next, *slow = head; while(fast && fast != slow) { fast = fast->next; if(fast) fast = fast->next; else return NULL; slow = slow->next; } if(!fast) return NULL; fast = fast->next; slow->next = NULL; int len1 = Cnt_link_len(head); int len2 = Cnt_link_len(fast); if(len1<len2) swap(head, fast); len1 = len1>=len2 ? len1-len2 : len2-len1; while(len1--) head = head->next; while(head && head != fast) { head = head->next; fast = fast->next; } if(!head) return NULL; return head; } };
参考代码:
/** * 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) { map<ListNode*, int>lm; while(head) { if(lm[head]==0) { lm[head] = 1; head = head->next; } else { return head; } } return NULL; }};
SECOND TRIAL, unordered_map is better.
/** * 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*, bool>mp; while(head) { if(mp[head]==true) return head; mp[head] = true; head = head->next; } return NULL; }};
0 0
- Leetcode_linked-list-cycle-ii
- LeetCode_linked-list-cycle-ii
- LeetCode_Linked List_Linked List Cycle II
- leetcode_Linked List Cycle
- LeetCode_Linked List Cycle
- LeetCode_Linked List_Linked List Cycle
- Leetcode_linked-list-cycle(c++ and python version)
- LeetCode_Linked List_Remove Duplicates from Sorted List II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Oracle 监听命令配置,虚拟宿主机访问的问题
- Storm DRPC环境搭建笔记
- 工厂方法模式--结合具体例子学习工厂方法模式
- 高斯日记
- 今日听完下一个七年该怎样度过后的感想
- Leetcode_linked-list-cycle-ii
- 微信公共平台开发接口(一)
- Servlet中Num和Date的国际化
- oracle 的to_char、to_number、to_date用法
- 搭建网络svn实战
- java学习视频
- 美国艾特贝(ITB)国际投资集团奖励、ITB计划、ITB投资、IT理财、选择(ITB)成就你我他。。。。
- 蓝桥杯2014年以前JAVA历年真题及答案整理——查找整数
- 内部类