Files
leetcode-daily/1.重排链表/笔记.md
2023-07-31 13:57:28 +08:00

38 lines
1.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## 快慢指针
快慢指针中的快慢指的是移动的步长即每次向前移动速度的快慢。例如可以让快指针每次沿链表向前移动2慢指针每次向前移动1次。
### 快慢指针的应用
#### 判断单链表是否为循环链表
让快慢指针从链表头开始遍历,快指针向前移动两个位置,慢指针向前移动一个位置;如果快指针到达NULL说明链表以NULL为结尾不是循环链表。如果 快指针追上慢指针,则表示出现了循环。
```
fast=slow=head;
fast=fast->next->next;
slow=slow->next;
whiletrue{
if (fast==NULL || fast->next==NULL)
return false;
else if (fast==slow || fast->next==slow)
return true;
else{
fast=fast->next->next;
slow=slow->next;
}
}
```
#### 在有序链表中寻找中位数
该方法在不借助计数器变量实现寻找中位数的功能。原理是快指针的移动速度是慢指针移动速度的2倍因此当快指针到达链表尾时慢指针到达中点。程序还要考虑链表结点个数的奇偶数因素当快指针移动x次后到达表尾1+2x说明链表有奇数个结点直接返回慢指针指向的数据即可。如果快指针是倒数第二个结点说明链表结点个数是偶数这时可以根据“规则”返回上中位数或下中位数或上中位数+下中位数)的一半。
```
while (fast&&slow)
{
if (fast->next==NULL)
return slow ->data;
else if (fast->next!= NULL && fast->next->next== NULL)
return (slow ->data + slow ->next->data)/2;
else
{
fast= fast->next;
fast= fast->next;
slow = slow ->next;
}
}
```