zoukankan      html  css  js  c++  java
  • 链表的中间结点

    876. 链表的中间结点

    给定一个带有头结点 head 的非空单链表,返回链表的中间结点。

    如果有两个中间结点,则返回第二个中间结点。

    示例 1:

    输入:[1,2,3,4,5]
    输出:此列表中的结点 3 (序列化形式:[3,4,5])
    返回的结点值为 3 。 (测评系统对该结点序列化表述是 [3,4,5])。
    注意,我们返回了一个 ListNode 类型的对象 ans,这样:
    ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, 以及 ans.next.next.next = NULL.
    

    示例 2:

    输入:[1,2,3,4,5,6]
    输出:此列表中的结点 4 (序列化形式:[4,5,6])
    由于该列表有两个中间结点,值分别为 3 和 4,我们返回第二个结点。
    
    #遍历 存入数组
    class Solution:
        def middleNode(self, head: ListNode) -> ListNode:
            nums = []
            if not head:
                return None
            while head:
                nums.append(head)
                head = head.next
            return nums[len(nums)//2]
    
    #两次遍历,得到长度
    class Solution:
        def middleNode(self, head: ListNode) -> ListNode:
            count = 0
            if not head:
                return None
            while head:
                count += 1
                head = head.next
            n = count//2
            while n:
                head = head.next
                n -= 1
            return head
    
    #快慢指针   慢指针每次移动一个,快指针每次移动2
    class Solution:
        def middleNode(self, head: ListNode) -> ListNode:
            if not head:
                return None
            slow,fast = head,head
            while fast and fast.next:
                slow = slow.next
                fast = fast.next.next
            return slow
    
  • 相关阅读:
    python 包与模块
    互斥锁与自旋锁
    TCP三次握手四次挥手
    缓存击穿、缓存穿透、缓存雪崩
    五种IO模型
    MySQL使用mysqldump进行数据备份
    golang数据库连接池参数设置
    golang代码文件目录组织、包目录组织学习笔记
    【转】如何用Vim提高开发效率
    emacs显示行号
  • 原文地址:https://www.cnblogs.com/gongyanzh/p/12554122.html
Copyright © 2011-2022 走看看