什么是ListNode? ListNode是一个用于创建链表的数据结构,它包含一个值和一个指向下一个节点的指针。
如何创建一个ListNode? 可以通过以下代码创建一个ListNode:
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
ListNode* current = head;
while (current != nullptr) {
// 处理当前节点
current = current->next;
}
ListNode* newNode = new ListNode(value);
newNode->next = current->next;
current->next = newNode;
ListNode* temp = current->next;
current->next = current->next->next;
delete temp;
ListNode* prev = nullptr;
ListNode* current = head;
ListNode* next = nullptr;
while (current != nullptr) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
head = prev;
bool hasCycle(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return false;
}
ListNode* slow = head;
ListNode* fast = head->next;
while (slow != fast) {
if (fast == nullptr || fast->next == nullptr) {
return false;
}
slow = slow->next;
fast = fast->next->next;
}
return true;
}