Linked List Cycle II
来源:互联网 发布:电脑淘宝怎么看信用 编辑:程序博客网 时间:2024/06/06 07:50
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
方法:寻找进入环的第一个节点。
参考https://leetcode.com/problems/linked-list-cycle-ii/。
/** * 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||!head->next) return NULL; ListNode* slow = head,*fast = head; bool first = true; while(first || slow != fast){ // ++step; first = false; if(slow->next) slow = slow -> next; else return NULL; if(fast->next && fast->next->next) fast = fast -> next -> next; else return NULL; } ListNode *cur = head; while(cur!=slow){ cur = cur -> next; slow = slow->next; } return cur; }};
0 0
- 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
- 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
- 2015山东省第六届acm省赛 C题Game!
- Dubbo与Zookeeper、SpringMVC整合和使用(入门级)
- Spring Bean的生命周期
- SpringMVC URL 正则表达式
- 10种简单的Java性能优化
- Linked List Cycle II
- ubuntu14.04 root登陆与自动登陆配置方法及出现问题解决
- 独立游戏开发日记(1)
- tar打包 解压
- 有关v$asm_attribute视图的一点记录
- 【安卓逆向】如何不用设置debuggable="true"就可以动态调试
- 从零开始学算法(四)搜索算法(二)(广度优先搜索)
- python读取excel
- EditText的imeOptions属性的使用