您的位置:首页 > 其它

leetcode Linked List Cycle & Linked List Cycle ||

2014-08-01 17:28 190 查看
如果知道链表环的相关前提知识,则较为方便就可以求出结果,具体分析可以查看博客/article/4814004.html

代码

Linked List Cycle

class Solution{
public:
bool hasCycle(ListNode * head)
{
ListNode *slow, *fast;

if(head == NULL||head->next==NULL)
return false;

slow = head;
fast = head->next;
while(slow->next!=NULL&&fast->next&&fast->next->next!=NULL)
{
if(slow==fast)
return true;

slow = slow ->next;
fast = fast->next->next;

}

return false;
}
};


Linked List Cycle ||

代码

class Solution {
public:
ListNode *detectCycle(ListNode *head) {

ListNode *slow, *fast;
if(head==NULL||head->next==NULL)
return NULL;
slow = head;
fast = head;
bool flag = false;

while(slow->next!=NULL&&fast->next!=NULL&&fast->next->next!=NULL)
{

slow = slow->next;
fast = fast->next->next;
if(slow == fast)
{
flag = true;
break;
}

}

if(flag)
{
ListNode *p;
p = head;
while(p!=slow)
{
p = p->next;
slow = slow ->next;

}
return p;

}
else
return NULL;
}
};



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: