当前位置:网站首页>【LeetCode】876-链表的中间结点
【LeetCode】876-链表的中间结点
2022-07-02 12:09:00 【酥酥~】
给定一个头结点为 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,我们返回第二个结点。
提示:
- 给定链表的结点数介于 1 和 100 之间。
#先得到链表长度,然后再次遍历取中间值
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def middleNode(self, head):
my_iter = head
cnt = 0
while my_iter:
my_iter = my_iter.next
cnt += 1
my_iter = head
for i in range(int(cnt/2)):
my_iter = my_iter.next
return my_iter
#将指针压入数列,然后随机访问取中间值
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def middleNode(self, head):
arr = []
n = 0
while head:
arr.append(head)
head = head.next
n+=1
return arr[int(n/2)]
边栏推荐
猜你喜欢

Map introduction

03.golang初步使用

百变大7座,五菱佳辰产品力出众,人性化大空间,关键价格真香

. Net again! Happy 20th birthday

语义分割学习笔记(一)

Equipped with Ti am62x processor, Feiling fet6254-c core board is launched!

Solve the problem of frequent interruption of mobaxterm remote connection

搭载TI AM62x处理器,飞凌FET6254-C核心板首发上市!

Map介绍

SQL stored procedure
随机推荐
NBA player analysis
数据分析常见的英文缩写(一)
Common English abbreviations for data analysis (I)
LeetCode刷题——统计各位数字都不同的数字个数#357#Medium
N皇后问题的解决
folium,确诊和密接轨迹上图
怎样从微信返回的json字符串中截取某个key的值?
PHP method to get the index value of the array item with the largest key value in the array
微信支付宝账户体系和支付接口业务流程
密码学基础知识
There are 7 seats with great variety, Wuling Jiachen has outstanding product power, large humanized space, and the key price is really fragrant
Markdown tutorial
终于搞懂了JS中的事件循环,同步/异步,微任务/宏任务,运行机制(附笔试题)
面对“缺芯”挑战,飞凌如何为客户产能提供稳定强大的保障?
高考分数线爬取
10_ Redis_ geospatial_ command
XML Configuration File
JVM architecture, classloader, parental delegation mechanism
LeetCode刷题——去除重复字母#316#Medium
Beijing rental data analysis