1 题目描述
2 解题思路
2.1 辅助数组
用一个辅助数组,记录链表里面的值,然后取数组中间的值
# 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):
lst=[head]
while(head.next!=None):
lst.append(head.next)
head=head.next
return(lst[len(lst)//2])
2.2 计算链表长度
先计算链表长度,再取一半长的那个值。
注意,偶数的话是取后面那个中间的数,所以这里需要(N+1)//2
# 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):
n=0
tmp=head
while(head.next!=None):
n+=1
head=head.next
print(n)
for i in range((n+1)//2):
tmp=tmp.next
return(tmp)
2.3 快慢指针
# 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):
fast=head
slow=head
while(fast!=None and fast.next!=None):
fast=fast.next.next
slow=slow.next
return slow