链表专题更新cpp代码

This commit is contained in:
3119005212
2021-04-28 18:28:00 +08:00
parent 6d96954aa7
commit afd452aeda
15 changed files with 627 additions and 12 deletions

View File

@@ -123,7 +123,9 @@ public class Solution {
![环形链表2](https://cdn.jsdelivr.net/gh/tan45du/photobed@master/photo/环形链表2.elwu1pw2lw0.gif)
**题目代码**
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;
}
};
```