[LeetCode]141. Linked List Cycle
题目描述
思路
快慢指针
代码
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
bool hasCycle(ListNode* head) {
if (head == NULL || head->next == NULL)
return false;
ListNode *slow = head, *fast = head;
while (fast) {
if (fast) {
fast = fast->next;
slow = slow->next;
}
if (fast)
fast = fast->next;
if (slow == fast)
return true;
}
return false;
}
};
int main() {
ListNode* l1 = new ListNode(1);
ListNode* l2 = new ListNode(2);
ListNode* l3 = new ListNode(3);
ListNode* l4 = new ListNode(4);
ListNode* l5 = new ListNode(5);
l1->next = l2;
l2->next = l3;
l3->next = l4;
l4->next = l5;
l5->next = l3;
Solution s;
cout << s.hasCycle(l1) << endl;
system("pause");
return 0;
}