嗯,回来了
中途间断,挺可怕的,捡回来不容易,刷题是的,跑步也是的,不容易,更不能轻易放弃
回来了,这段时间开始专门刷一下链表相关的题目,先从一道简单的来吧
找一个链表的中间节点:https://leetcode-cn.com/problems/middle-of-the-linked-list/description/
都是套路啊,当然可以很直接的先遍历一遍,得到链表的长度,然后处理,不过有一个比较常见的“讨巧”的思路,就是快慢指针。
代码就非常直接和简单咯:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def middleNode(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
slow = head
fast = head
while fast != None and fast.next != None:
slow = slow.next
fast = fast.next.next
return slow