判断是否为环形链表算法
输出的案例答案是错的,应该是链表初始化的问题,但是不知道哪错了
#include <iostream>
using namespace std;
struct ListNode{
int val;
struct ListNode* next;
};
bool hasCycle(ListNode* head) {
ListNode* fast = head;
ListNode* slow = head;
while (fast != nullptr) {
fast = fast->next;
if (fast != nullptr) {
fast = fast->next;
}
if (slow == fast) {
return true;
}
slow = slow->next;
}
return false;
}
int main() {
ListNode node1 = { 3, NULL };
ListNode node2 = { 2, NULL };
ListNode node3 = { 0, NULL };
ListNode node4 = { -4, NULL };
node1.next = &node2;
node2.next = &node3;
node3.next = &node4;
ListNode* head = &node1;
bool ans = hasCycle(head);
cout << boolalpha << ans << endl;
return 0;
}