Leetcode NO.142 Linked List Cycle II
来源:互联网 发布:三菱a系列plc编程手册 编辑:程序博客网 时间:2024/04/30 00:19
题目要求如下:
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?
我的最开始的思路如下:
1,设置两个pointer, 一个快,一个慢,快的每次前进两次,慢的一次,这样就是如果有cycle的话,则他们必会相遇
2,以相遇点为起点,仍然是两个pointer,当快的追上慢的的时候,慢的走过的路程恰好是cycle的length
3,然后把两个pointer起点设为head,fast先行length的路程。然后slow的也开始前进,这两个pointer每次都是往前走一步。相遇点则为cycle的起点
总之,我太傻了,这三部里面有很多是多余内容。。
下面是精简后的代码:
class Solution {public: ListNode *detectCycle(ListNode *head) { ListNode* fast_ptr = head; ListNode* slow_ptr = head; /* check if it contain a cycle */ do { if (fast_ptr == NULL || fast_ptr->next == NULL) return NULL; fast_ptr = fast_ptr->next->next; slow_ptr = slow_ptr->next; } while (fast_ptr != slow_ptr); slow_ptr = head; while (slow_ptr != fast_ptr) { fast_ptr = fast_ptr->next; slow_ptr = slow_ptr->next; } return slow_ptr; }};首先,第2步就是没有用的,因为第一次这两个pointer相遇的时候,slow走过的路程就是cycle length。同时fast盒slow所处的位置也是第散步中fast行完cycle length路程后的位置,此时,只需要将slow指向head,然后两个pointer每次往前走一步,相遇点即为cycle起点。
0 0
- Leetcode NO.142 Linked List Cycle II
- LeetCode--No.142--Linked List Cycle II
- LeetCode.142(141) Linked List Cycle && Linked List Cycle (II)
- LeetCode 142 Linked List Cycle II
- LeetCode 142 Linked List Cycle II
- LeetCode: Linked List Cycle II [142]
- [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
- [leetcode-142]Linked List Cycle II(c)
- leetcode 142: Linked List Cycle II
- leetCode #142 Linked List Cycle II
- Leetcode #142 Linked List Cycle II
- 142 Linked List Cycle II [Leetcode]
- 【LEETCODE】142-Linked List Cycle II
- Zygote进程的启动
- SequoiaDB集群的搭建(一)
- Windows Server 2008远程桌面端口更改方法
- 网站优化推广怎么选取关键词?
- [Salesforce] Solution of custom page cannot redirect on Salesforce1
- Leetcode NO.142 Linked List Cycle II
- 单例模式并不简单
- 对涂胶工艺认识的误区之六--胶条的宽高比是靠机器调整的
- 你说的话是什么意思啊华南理工大学自考招生?
- 无法打开物理文件 操作系统错误5 5120
- Entity framework 连接mysql
- 来自某高人的演讲
- 自己封装的简单Jquery分页插件
- Windows Server 2008 防火墙开放 Oracle 的1521端口 .