您的位置:首页 > 其它

4.24 leetcode -24 linked-list-cycle

2017-08-29 15:14 344 查看
题目描述

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

Follow up:

Can you solve it without using extra space?

给一个链表,看是否有循环,不用额外控件,一个一步走,一个两步走,能汇合就有cycle

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