LeetCode 142. Linked List Cycle II
来源:互联网 发布:天津中年同志软件 编辑:程序博客网 时间:2024/06/15 12:55
142. Linked List Cycle II
Description
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?
Analysis
这道题的意思就是判断链表中是否存在着环,如果存在则返回环则返回环的起点。
这道的要点在于它不仅要判断是否是环,还要返回环的起点。
我对这道题的解法是判断是否是环再找起点。
判断是否是环比较简单,利用两个指针一个跳一步,一个跳两步,如果有重合,则说明存在环。
而找到起点,则比较技巧了。
假设环程度为len,second走到环的起点长度为m,则first走的长度为2m,而假设second从环起点走到相遇点的的长度为n,则此时first走了2n。
则可得到len = 2m+2n-m-n = m+n,而现在first已经在环中走了长度n,还需要m才能走到环起点。而second走到环起点的长度为m。
所以可以利用一个从头开始的指针,跟first一起一次跳一步,当这两个相遇后就是环起点。
Code
/** * 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 ; //if(head->next == NULL) return head; ListNode * first = head; ListNode * second = head; int res = 0; while(first!=NULL&&first->next!=NULL){ second = second->next; first = first->next->next; if(first == second){ //break; //res=1; ListNode * ans = head; while(1){ if(ans == first) return first; else{ ans= ans->next; first = first->next; } } } } return NULL; //if(res==0) return NULL; }};
0 0
- [LeetCode]141. Linked List Cycle【&142. Linked List Cycle II】
- leetcode--141. Linked List Cycle&&142. Linked List Cycle II
- LeetCode 141. Linked List Cycle && 142. Linked List Cycle II
- 142. Linked List Cycle II leetcode list
- LeetCode 142. Linked List Cycle II
- [LeetCode]142.Linked List Cycle II
- [leetcode] 142.Linked List Cycle II
- [leetcode] 142. Linked List Cycle II
- leetcode 142. Linked List Cycle II
- [Leetcode]142. Linked List Cycle II @python
- [LeetCode]142. Linked List Cycle II
- 142. Linked List Cycle II LeetCode
- LeetCode:142. Linked List Cycle II
- LeetCode--142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- LeetCode *** 142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- java 集合(set、list、map、stack、queue)的用法
- 从菜鸟到架构师(九)
- Java8特性总结以及Java的未来
- 第十三单元练习
- 支付功能----第三方支付公司
- LeetCode 142. Linked List Cycle II
- LeetCode | 15. 3Sum(三数和为定值)
- android sdk配置
- Java开发中的23种设计模式详解
- Python源码学习笔记 3 字符串对象
- Largest Rectangle in a Histogram POJ
- 关于JS的逻辑运算题之if的使用
- Hibernate总结笔记之三
- eclipse git 提交时提示 “There are no staged files”