Linked List Cycle II 求单链表环的入口
2015-05-20 20:54
176 查看
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?
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ /* 假设ptr1需要m步第一次走到环的开始节点,那么ptr2应该走到了环的第m个位置(注意:这里是指环里的位置,ptr1在0处,ptr2在m处)。ptr2每次都比ptr1多走一步且它们都在环内,所以需要n-m步(n是环的大小),才能追上ptr1,达到重合。这个重合位置是[2*(n-m)+m-x*n]%n=n-m,这样我们就可以知道,重合的位置距离环开始节点有m步,head距离环开始节点也是m步。 */ class Solution { public: ListNode *detectCycle(ListNode *head) { if(head==NULL) return NULL; ListNode *slow,*fast; slow=head; fast=head; int f=0; while(fast!=NULL&&fast->next!=NULL) { fast=fast->next->next; slow=slow->next; if(slow==fast) { f=1; break; } } if(!f) return NULL; slow=head; while(slow!=fast) { slow=slow->next; fast=fast->next; } return slow; } };
相关文章推荐
- 求单链表环的入口结点 Linked List Cycle II
- Leetcode Linked List Cycle II 循环链表入口
- Linked List Cycle leetcode II java (寻找链表环的入口)
- Linked List Cycle II 找链表环入口 @LeetCode
- 判断链表是否有环及环入口点的求法(Linked List Cycle II )
- Linked List Cycle leetcode II java (寻找链表环的入口)
- 142 Linked List Cycle II(如果链表有环,找到入口结点Medium)
- 判断链表是否有环及环入口点的求法(Linked List Cycle II )
- LeetCode Linked List Cycle II 单链表环2 (找循环起点)
- 2.2.12—单链表—Linked List Cycle II
- 142. Linked List Cycle II
- LeetCode:Linked List Cycle II
- ★ Linked List Cycle II -- LeetCode
- [LeetCode] Linked List Cycle II Solution
- [leetCode]Linked List Cycle I+II
- LeetCode142 Linked List Cycle II
- leetcode — linked-list-cycle-ii
- LeetCode Linked List Cycle II
- Linked List Cycle I,II, Partition List
- Linked List Cycle II