您的位置:首页 > 其它

141-Linked List Cycle

2017-11-05 13:29 239 查看
难度:easy

类别:linked list

1.题目描述

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

Follow up:

Can you solve it without using extra space?

2.算法分析

用了一种比较取巧的方法。

如果一个单向链表中有环的话,那么不存在节点的next指针为NULL,因而可以遍历链表并且进行计数,如果计数到达MAX(设定为10000),姑且表明该链表中含有环。

3.代码实现

#define MAX 10000
bool hasCycle(ListNode *head) {
if (head == NULL || head->next == NULL) return false;
int count = 0;
while (head != NULL) {
count++;
head = head->next;
if (count >= MAX) return true;
}
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 141 cycle-list