您的位置:首页 > 其它

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保存已经访问过的节点的地址。

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: