您的位置:首页 > 编程语言 > Go语言

leetcode: (141) Linked List Cycle

2015-09-23 22:55 399 查看
【Question】

Given a linked list, determine if it has a cycle in it.

Follow up:

Can you solve it without using extra space?

无环的话,必定最后一个节点指向NULL。有环的话,肯定会指向前面的节点。这一个不动步长的节点,一个每次移动一个节点,另一个每次移动两个节点,有环的话总会在一个接点处相遇。

class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *first,*second;
first=head;
second=head;
while(second!=NULL)
{
first=first->next;
second=second->next;
if(second==NULL) return false;
second=second->next;
if(first==second&&first!=NULL) return true;
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  algorithms leetcode 链表