函数hasCycle采用Floyd快慢指针法判断一个单链表中是否存在环,链表的头节点为head,即用两个指针 在链表上前进:slow 每次走 1 步,fast 每次走 2 步,若存在环,fast 终会追上 slow(相遇);若无环, fast 会先到达 nullptr,则横线上应填写( )。
struct Node {
int val;
Node *next;
Node(int x) : val(x), next(nullptr) {}
};
bool hasCycle(Node *head) {
if (!head || !head->next)
return false;
Node* slow = head;
Node* fast = head->next;
while (fast && fast->next) {
if (slow == fast) return true;
_______________________ // 在此填入代码
}
return false;
}
正在加载题目数据…
子题
该题型需在试卷/作业中作答,单题练习暂不支持
答案解析