您的位置:首页 > 其它

Linked List Cycle

2016-02-01 09:34 211 查看
两个指针系列

This question is just something like if you know the trick then you can do it, otherwise just no way to solve it.

Note:

1. The faster one move 2 steps and slower one move one step each time

2. Be careful  when you are access node->next,  you should check node first. same logic apply to node->next->next

3. Regarding head node, handle the special cases first.

class Solution {
public:
bool hasCycle(ListNode *head) {
if (head == NULL || head->next == NULL)
return false;
ListNode *n1 = head;
ListNode *n2 = head;
while (n2 != NULL && n2->next != NULL)
{
n2 = n2->next->next;
n1 = n1->next;
if (n2 == n1)
return true;
}
return false;

}
};

Just to make the code cleaner, there is no need to check 

if (head == NULL || head->next == NULL)


at the begin, you can embed this also inside of the while loop, but it make more clear if we check at the beginning. 

Follow up:

Solve it without extra space O(1) solution. This is already a solution with O(1) space since it just create a pointer point to existing one but no new or malloc so it is still O(1).
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: