您的位置:首页 > 其它

141.leetcode Linked List Cycle(easy)[链表是否有环 快慢指针]

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