判断链表中是否存在环
让快慢指针从链表头开始遍历,快指针向前移动两个位置,慢指针向前移动一个位置;如果快指针到达NULL,说明链表以NULL为结尾,不是循环链表。如果 快指针追上慢指针,则表示出现了循环。
bool hasCycle(ListNode *head) {
if(head == nullptr || head -> next == nullptr)
return false;
ListNode *slow = head, *fast = head;
while(fast && fast -> next){
slow = slow -> next;
fast = fast -> next -> next;
if(slow == fast)
return true;
}
return false;
}
获取链表中点
快指针的移动速度是慢指针移动速度的2倍,因此当快指针到达链表尾时,慢指针到达中点。
如果节点是偶数个,找到的节点将是中间偏右边的那个节点,如果想获取中间偏左的节点,可以让fast = head -> next;
ListNode *slow = head, *fast = head;
while(fast != nullptr && fast -> next != nullptr) {
slow = slow -> next;
fast = fast -> next -> next;
}