您的位置:首页 > 运维架构

LeetCode:Linked List Cycle

2014-08-31 16:48 281 查看
Given a linked list, determine if it has a cycle in it.

Follow up:

Can you solve it without using extra space?

bool hasCycle(ListNode *head)
{
<span style="white-space:pre">	</span>if(head == NULL)
<span style="white-space:pre">		</span>return false;

<span style="white-space:pre">	</span>ListNode* pslow = head;
<span style="white-space:pre">	</span>ListNode* pfast = head;

<span style="white-space:pre">	</span>while(pfast != NULL && pfast ->next != NULL)
<span style="white-space:pre">	</span>{
<span style="white-space:pre">		</span>pslow = pslow->next;
<span style="white-space:pre">		</span>pfast = pfast->next->next;
<span style="white-space:pre">		</span>if(pfast == pslow)
<span style="white-space:pre">			</span>return true;
<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span>return false;
}
分析:用到了快慢指针。如果快指针追上了慢指针,说明存在循环,否则没有。

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