您的位置:首页 > 其它

[LeetCode OJ]Linked List Cycle

2014-10-21 21:37 197 查看
Given a linked list, determine if it has a cycle in it.

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) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if (head == NULL) {
return false;
}
if (head->next == NULL) {
return false;
}
if (head->next == head) {
return true;
}

ListNode *y = head->next;
ListNode *x = head->next->next;

while(x != NULL && y != NULL) {
x = x->next;
if (x == NULL)
break;
x = x->next;
y = y->next;
if (x == y)
break;
}
return x == y;
}
};


标准做法是使用两个指针,一个每次往前走2步,一个每次往前走1步,如果两个指针相遇,即说明链表有环,时间复杂度为O(N),空间复杂度为O(1)。

这篇文章蛮有帮助,也是按着这个思路实现的代码:经典面试题 之 单链表找环
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: