<leetcode系列> Linked List Cycle II
来源:互联网 发布:linux系统监控命令 编辑:程序博客网 时间:2024/06/08 00:33
Linked List Cycle II
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?
题目大意:
给定一个链表,如果该链表中含有环,则返回这个环开始的那个节点的地址,如果没有环,则返回NULL.
原题链接: https://leetcode.com/problems/linked-list-cycle-ii/
这个题目接Linked List Cycle, 也是快慢指针的运用.示意图如下:
如上图, 在环的前面,长度为a(即, 从头结点开始,走a步到环的入口), 环的周长为b(即,从环的入口开始,走b步回到入口处).
那么快慢指针每次分别走2步和1步,设走了x步相遇,则:
则,可知:
那么,相遇点从环入口处计数,已经走了
综上,设快慢指针相遇点为meet, 令一个指针为p, p从头指针出开始走, 每次走一步, meet也跟随p每次走一步.那么他们会在环的入口处相遇.
代码如下:
// 有环的话,返回快慢指针相遇的地址; // 无环的话,返回NULL struct ListNode* judgeCycle(struct ListNode *head) { int slowStep = 1; int fastStep = 2; struct ListNode* slow = head; struct ListNode* fast = head; while (true) { for (int j = 0; j < fastStep; ++j) { fast = fast->next; if (NULL == fast) { return NULL; } } for (int i = 0; i < slowStep; ++i) { slow = slow->next; } if (fast == slow) { return fast; } }}struct ListNode *detectCycle(struct ListNode *head) { if ((NULL == head) || (NULL == head->next)) { return NULL; } struct ListNode* p = head; struct ListNode* meet = judgeCycle(head); if (NULL == meet) { return NULL; } while (true) { if (p == meet) { return p; } p = p->next; meet = meet->next; }}
0 0
- 【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
- [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
- Linked List Cycle II -- LeetCode
- ZOJ.2773 Triangular Sums【水~】 2015/09/24
- Nginx的功能特性
- C/C++ 之 操作符重载
- NSNotification通知的使用
- 循环结构 -- 2015/09/24
- <leetcode系列> Linked List Cycle II
- ITOO4.0项目问题汇总
- Poj.3086 Triangular Sums【水~】 2015/09/24
- 判断点是否在三角形内
- jquery的ajax同步和异步
- C/C++结构体字节对齐详解
- 用两个栈实现队列
- Android Scroller完全解析,关于Scroller你所需知道的一切
- NGUI 3D菜单