给定一个头结点为 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.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/middle-of-the-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
# 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
"""
# arr = [head]
# while arr[-1].next:
# arr.append(arr[-1].next)
# return arr[len(arr)/2]
# slow = fast = head
# while fast and fast.next:
# fast = fast.next.next
# slow = slow.next
# return slow
cur = head
count = 0
while cur:
count += 1
cur = cur.next
# print count
if count == 1:
return head
mid = count/2
print mid
node = head
count = 0
while node:
count += 1
if count == mid:
return node.next
node = node.next
网友评论