给定一个带有头结点 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:通过链表长度得到index
思路:通过遍历得到链表的长度,然后长度除以2得到中间节点的index,返回中间结点及之后的节点。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def middleNode(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
count = 0
cur = head
while cur:
cur = cur.next
count+=1
if count%2 == 0:
index = int(count/2)+1
else:
count = count+1
index = int(count/2)
count1 = 1
cur2 = head
while cur2:
if count1 != index:
cur2 = cur2.next
else:
return cur2
成功
显示详情
执行用时 : 28 ms, 在Middle of the Linked List的Python提交中击败了100.00% 的用户
内存消耗 : 11.8 MB, 在Middle of the Linked List的Python提交中击败了32.43% 的用户
方法2:数组
将每段链表存储到列表中,列表的长度就是链表中元素的个数,长度除以2之后向下取整(int()函数),对应的索引正好是符合要求的链表的中间位置,所以返回列表的第index个值。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def middleNode(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
node_list = []
cur = head
while cur:
node_list.append(cur)
cur = cur.next
n = len(node_list)
index = int(n/2)
return node_list[index]
显示详情
执行用时 : 48 ms, 在Middle of the Linked List的Python提交中击败了11.82% 的用户
内存消耗 : 11.8 MB, 在Middle of the Linked List的Python提交中击败了36.03% 的用户
方法3:快慢指针法
设定两个指针,快指针是慢指针速度的2倍,所以当快指针到链表的最后一个元素(链表节点个数为奇数)或者指针指到最后的None(链表节点个数为偶数)时,慢指针正好在链表中间。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def middleNode(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
slow,fast = head,head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
成功
显示详情
执行用时 : 52 ms, 在Middle of the Linked List的Python提交中击败了11.82% 的用户
内存消耗 : 11.8 MB, 在Middle of the Linked List的Python提交中击败了31.53% 的用户