什么是ListNode? ListNode是一個(gè)用于創(chuàng)建鏈表的數(shù)據(jù)結(jié)構(gòu),它包含一個(gè)值和一個(gè)指向下一個(gè)節(jié)點(diǎn)的指針。
如何創(chuàng)建一個(gè)ListNode? 可以通過(guò)以下代碼創(chuàng)建一個(gè)ListNode:
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
ListNode* current = head;
while (current != nullptr) {
// 處理當(dāng)前節(jié)點(diǎn)
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;
}