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

138 lines
4.8 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

> **[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/)
head
** 1**
```java
[1,2,3,4,5]
3
```
>
** 2**
```java
[1,2,3,4,5,6]
4
```
>
****
K
OKOK
k-1
slow
![](https://img-blog.csdnimg.cn/20210321131249789.gif)
****
Java Code:
```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;
}
}
```
C++ Code:
```cpp
class Solution {
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;
}
};
```
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:
```python
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
```
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
}
}
```