algorithm-base/animation-simulation/链表篇/面试题 02.03. 链表中间节点.md

138 lines
4.8 KiB
Java
Raw Normal View History

2021-03-20 08:57:12 +00:00
> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
#### [876. ](https://leetcode-cn.com/problems/middle-of-the-linked-list/)
2021-03-19 07:07:33 +00:00
2021-07-15 16:06:52 +00:00
head
2021-03-19 07:07:33 +00:00
** 1**
```java
[1,2,3,4,5]
3
```
2021-07-15 16:06:52 +00:00
>
2021-03-19 07:07:33 +00:00
** 2**
```java
[1,2,3,4,5,6]
4
```
2021-07-15 16:06:52 +00:00
>
2021-03-19 07:07:33 +00:00
2021-07-15 16:06:52 +00:00
****
2021-03-19 07:07:33 +00:00
K
OKOK
k-1
2021-07-15 16:06:52 +00:00
slow
2021-03-19 07:07:33 +00:00
2021-03-21 05:13:12 +00:00
![](https://img-blog.csdnimg.cn/20210321131249789.gif)
2021-03-19 07:07:33 +00:00
2021-04-28 10:28:00 +00:00
****
Java Code:
2021-03-19 07:07:33 +00:00
```java
class Solution {
public ListNode middleNode(ListNode head) {
ListNode fast = head;//快指针
ListNode slow = head;//慢指针
//循环条件,思考一下跳出循环的情况
while (fast!=null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
//返回slow指针指向的节点
return slow;
}
}
```
2021-04-28 10:28:00 +00:00
C++ Code:
```cpp
2021-07-12 09:24:38 +00:00
class Solution {
2021-04-28 10:28:00 +00:00
public:
ListNode* middleNode(ListNode* head) {
ListNode * fast = head;//快指针
ListNode * slow = head;//慢指针
//循环条件,思考一下跳出循环的情况
while (fast != nullptr && fast->next != nullptr) {
fast = fast->next->next;
slow = slow->next;
}
//返回slow指针指向的节点
return slow;
}
};
```
2021-07-12 09:24:38 +00:00
JS Code:
```js
var middleNode = function(head) {
let fast = head;//快指针
let slow = head;//慢指针
//循环条件,思考一下跳出循环的情况
while (fast && fast.next) {
fast = fast.next.next;
slow = slow.next;
}
//返回slow指针指向的节点
return slow
};
```
Python Code:
2021-07-15 16:06:52 +00:00
```python
2021-07-12 09:24:38 +00:00
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
fast = head #
slow = head #
#
while fast is not None and fast.next is not None:
fast = fast.next.next
slow = slow.next
# slow
return slow
```
2021-07-17 14:28:06 +00:00
Swift Code
```swift
class Solution {
func middleNode(_ head: ListNode?) -> ListNode? {
var fast = head //快指针
var slow = head //慢指针
//循环条件,思考一下跳出循环的情况
while fast != nil && fast?.next != nil {
fast = fast?.next?.next
slow = slow?.next
}
//返回slow指针指向的节点
return slow
}
}
```