Linked List Cycle II (leetcode)
2014-11-18 16:07
405 查看
题目:
Given a linked list, return the node where the cycle begins. If there is no cycle, return
Follow up:
Can you solve it without using extra space?
题目来源:https://oj.leetcode.com/problems/linked-list-cycle-ii/
解题思路:第一个指针first每次经过一个节点,第二个指针second每次经过2个节点,则相遇时,s2=2s1,即第二个指针走过的位置是第一个指针的两倍,因为速度是其2倍。这样,假设链头到环位置为x,环到他们相遇的位置为a,则s1=x+a+n1*L,L是环长,s2=x+a+n2*L,由于s2=2s1,所以x+a=(n2-n1)*L,此时,若再有一个指针third从head开始走,first从与second相遇的地方开始走,则他们必然会在环开始的地方相遇。
参考:《leetcode题解》
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?
题目来源:https://oj.leetcode.com/problems/linked-list-cycle-ii/
解题思路:第一个指针first每次经过一个节点,第二个指针second每次经过2个节点,则相遇时,s2=2s1,即第二个指针走过的位置是第一个指针的两倍,因为速度是其2倍。这样,假设链头到环位置为x,环到他们相遇的位置为a,则s1=x+a+n1*L,L是环长,s2=x+a+n2*L,由于s2=2s1,所以x+a=(n2-n1)*L,此时,若再有一个指针third从head开始走,first从与second相遇的地方开始走,则他们必然会在环开始的地方相遇。
参考:《leetcode题解》
#include<iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ListNode *detectCycle(ListNode *head) { if(head==NULL) return NULL; ListNode *first=head,*second=head; bool flag=false; while(second!=NULL && second->next!=NULL) { first=first->next; second=second->next->next; if(first==second) { flag=true; break; } } if(!flag) return NULL; ListNode *third=head; while(first!=third) { first=first->next; third=third->next; } return third; } int main() { ListNode *head=new ListNode(1); head->next=new ListNode(2); head->next->next=new ListNode(3); head->next->next->next=head->next;/**/ ListNode *result=detectCycle(head); system("pause"); return 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 141 & 142, medium] Linked List Cycle (I and II)
- [LeetCode] - Linked List Cycle II
- [leetcode]Linked List Cycle II
- LeetCode: Linked List Cycle II
- [算法][LeetCode]Linked List Cycle & 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