Linked List Cycle II
2014-08-11 17:26
375 查看
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?
思路:依次遍历链表,使用set保存已经访问过的节点的地址。
上述方法需要大量额外空间。为了满足常空间复杂度要求,参考网上的方法:使用两个指针slow和fast,分别以1和2的速度遍历链表。若链表中存在环,则两个指针必然会在某时刻相遇。且首次相遇时,两个指针经过的节点数目一定满足2倍关系。
如上图:slow和fast经过的节点数目分别为:x+y和x+2*y+z,由2*(x+y)=x+2*y+z有,x = z。
还有一种方法:依次遍历链表,将当前访问节点的地址保存到其val字段中。不过,该方法会破坏原始链表的数据,并且若原始链表的某个节点的val字段的值与其地址值本身就相同,则算法将失效。
Follow up:
Can you solve it without using extra space?
思路:依次遍历链表,使用set保存已经访问过的节点的地址。
class Solution { public: ListNode *detectCycle( ListNode *head ) { unordered_set<ListNode*> nodeSet; while( head ) { if( nodeSet.count( head ) ) { return head; } nodeSet.insert( head ); head = head->next; } return 0; } };
上述方法需要大量额外空间。为了满足常空间复杂度要求,参考网上的方法:使用两个指针slow和fast,分别以1和2的速度遍历链表。若链表中存在环,则两个指针必然会在某时刻相遇。且首次相遇时,两个指针经过的节点数目一定满足2倍关系。
如上图:slow和fast经过的节点数目分别为:x+y和x+2*y+z,由2*(x+y)=x+2*y+z有,x = z。
class Solution { public: ListNode *detectCycle( ListNode *head ) { if( !head || !head->next ) { return 0; } ListNode *slow = head, *fast = head; while( fast ) { slow = slow->next; fast = fast->next; if( fast ) { fast = fast->next; } if( fast && fast == slow ) { slow = head; while( slow != fast ) { slow = slow->next; fast = fast->next; } return slow; } } return 0; } };
还有一种方法:依次遍历链表,将当前访问节点的地址保存到其val字段中。不过,该方法会破坏原始链表的数据,并且若原始链表的某个节点的val字段的值与其地址值本身就相同,则算法将失效。
class Solution { public: ListNode *detectCycle( ListNode *head ) { while( head ) { if( (int)head == head->val ) { return head; } head->val = (int)head; head = head->next; } return 0; } };
相关文章推荐
- CODE 139: Linked List Cycle II
- leetcode题目:Linked List Cycle和Linked List Cycle II
- Linked List Cycle II
- leetcode-Linked List Cycle I & II
- leetcode_c++:链表:Linked List Cycle II(142)
- [LeetCode] Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Leetcode-Linked List Cycle II
- Leetcode 142 Linked List Cycle II
- LeetCode - Linked List Cycle II
- [leet code] Linked List Cycle II
- 【Leetcode】Linked List Cycle II (Walker_Runner)
- 142. Linked List Cycle II
- LeetCode---Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle I和II 以及扩展
- [LeetCode 142] Linked List Cycle II
- Leetcode在线编程linked-list-cycle-ii