LeetCode 141. Linked List Cycle
Solution1:我的答案
快慢指针即可
/**
* 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;
struct ListNode *slow, *fast;
if (head->next)
slow = head->next;
else
return false;
if (head->next->next)
fast = head->next->next;
else
return false;
while (slow->next && fast->next && fast->next->next) {
if (slow == fast)
return true;
slow = slow->next;
fast = fast->next->next;
}
return false;
}
};
Solution2:更简单的写法
参考网址:http://www.cnblogs.com/grandyang/p/4137187.html
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) return true;
}
return false;
}
};
本文介绍了解决LeetCode141题“链表环检测”的两种方法。第一种方法使用快慢指针来判断链表中是否存在环。第二种方法简化了第一种方法的实现,使代码更加简洁。这两种方法都是通过两个速度不同的指针遍历链表来判断是否存在环。
810

被折叠的 条评论
为什么被折叠?



