您的位置:首页 > 编程语言 > C语言/C++

[leetcode] 【链表】141. Linked List Cycle

2016-06-02 16:05 561 查看
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) {
ListNode *fast=head,*slow=head;
while(fast&&fast->next)
{
fast=fast->next->next;
slow=slow->next;
if(fast==slow)
return true;
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode cpp