什么是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;
}