mirror of
https://github.com/chefyuan/algorithm-base.git
synced 2025-08-03 22:41:58 +00:00
链表专题更新cpp代码
This commit is contained in:
@@ -123,7 +123,9 @@ public class Solution {
|
||||
|
||||

|
||||
|
||||
**题目代码**
|
||||
|
||||
Java Code:
|
||||
|
||||
```java
|
||||
public class Solution {
|
||||
@@ -153,3 +155,34 @@ public class Solution {
|
||||
}
|
||||
```
|
||||
|
||||
C++ Code:
|
||||
|
||||
```cpp
|
||||
class Solution {
|
||||
public:
|
||||
ListNode *detectCycle(ListNode *head) {
|
||||
//快慢指针
|
||||
ListNode * fast = head;
|
||||
ListNode * low = head;
|
||||
//设置循环条件
|
||||
while (fast != nullptr && fast->next != nullptr) {
|
||||
fast = fast->next->next;
|
||||
low = low->next;
|
||||
//相遇
|
||||
if (fast == low) {
|
||||
//设置一个新的指针,从头节点出发,慢指针速度为1,所以可以使用慢指针从相遇点出发
|
||||
ListNode * newnode = head;
|
||||
while (newnode != low) {
|
||||
low = low->next;
|
||||
newnode = newnode->next;
|
||||
}
|
||||
//在环入口相遇
|
||||
return low;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
|
Reference in New Issue
Block a user