blog/source/_posts/2020-03-26-leetcode-876.md
Ching 9690121403 feat(init project): add all existing files
add all existing files

Signed-off-by: Ching <loooching@gmail.com>
2022-02-02 19:04:18 +08:00

68 lines
1.3 KiB
Markdown
Raw Permalink 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.

---
title: leetcode-876
date: 2020-03-26 21:18:41
tags:
categories: leetcode
---
### 876. 链表的中间结点
[题目](https://leetcode-cn.com/problems/middle-of-the-linked-list/)
<!--more-->
思路是遍历一遍得到整个链表,讲每个 node 放进一个 list就可以通过下标得到中间的。
```python
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
l = []
n = head
while n.next:
l.append(n)
n = n.next
l.append(n)
return l[len(l)//2]
#44 ms 13.7 MB
```
看官方解答,还有一个骚操作,通过两个速度不一样的指针,一个一次走一步,一个两次走一步,快的走到底时,慢的就在中间了。
```python
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
作者LeetCode-Solution
链接https://leetcode-cn.com/problems/middle-of-the-linked-list/solution/lian-biao-de-zhong-jian-jie-dian-by-leetcode-solut/
来源力扣LeetCode
著作权归作者所有商业转载请联系作者获得授权非商业转载请注明出处
```