Given a non-empty, singly linked list with head node head, return a middle node of linked list.

If there are two middle nodes, return the second middle node.

Example 1:

Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3. (The judge's serialization of this node is [3,4,5]).
Note that we returned a ListNode object ans, such that:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.

Example 2:

Input: [1,2,3,4,5,6]
Output: Node 4 from this list (Serialization: [4,5,6])
Since the list has two middle nodes with values 3 and 4, we return the second one.

Note:

  • The number of nodes in the given list will be between 1 and 100.

We can use two trappers 'slow' and 'fast' to help us to find the answer.

Each time, 'slow' will jump to the next node and 'fast' will jump to the next two nodes.

When 'fast' or 'fast.node' reaches the end node, 'slow' reaches the answer.

# 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=fast=head
while fast and fast.next:
slow=slow.next
fast=fast.next.next
return slow

  

最新文章

  1. java分享第十一天(接口测试)
  2. java的三大框架(一)
  3. 小议map排序问题
  4. https封装类,支持get/post请求
  5. virt-XXX
  6. Qt 中使用vector
  7. POJ 1860 Currency Exchange 毫无优化的bellman_ford跑了16Ms,spfa老是WA。。
  8. hdu 4775 Infinite Go(暴力)
  9. C++面向对象编程初步
  10. 在TreeWidget中增加右键菜单功能 以及TreeWidget的基本用法
  11. h和.cpp文件的区别
  12. XPSP2 PSDK(还有lostspeed)
  13. 201521123016《java程序设计》第4周学习总结
  14. err:安装程序试图挂载映像 1(缺少ISO 9660图像)
  15. 使用javascript和css模拟帧动画的几种方法浅析
  16. JSON语法
  17. 比特币中的Base58 编码
  18. Node 7.6默认支持Async/Await
  19. sencha touch 带本地搜索功能的selectfield(选择插件)
  20. delphi连接mysql (通过libmysql.dll连接)

热门文章

  1. RetinaNet论文理解
  2. vs下手敲git命令补遗
  3. URAL 1741 Communication Fiend
  4. 详解Mybatis通用Mapper介绍与使用
  5. 12月17日周日 form_for的部分理解。belongs_to的部分理解
  6. codeforces 559b//Equivalent Strings// Codeforces Round #313(Div. 1)
  7. android--------Android内存分析工具的使用
  8. RAC配置(启停库)
  9. kill word out e ef en em
  10. 2.strcpy使用注意(2)