Given the head
of singly linked list, return the middle node of the linked list.
If there are two middel nodes, return the second middle node.
Input : head = [1,2,3,4,5]
Output : [3,4,5]
Explanation : The middle node of the list is node 3.
Input : head = [1,2,3,4,5,6]
Output : [4,5,6]
Explanation : Since the list has two middle nodes with values 3 and 4, we return the second one.
ListNode{val: 1, next: ListNode{val: 2, next: ListNode{val: 3, next: ListNode{val: 4, next: ListNode{val: 5, next: None}}}}}
# 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):
"""
:type head: ListNode
:rtype: ListNode
"""
length = 0
tmp = head
print(head)
while True:
length += 1
if tmp.next == None :
break
tmp = tmp.next
target = head
for _ in range(length//2) :
target = target.next
return target
결과 Runtime : 38ms, faster than 5.84% of Python online submission for Middle of the Linked List.
=> 더 빨리 수행될 수 있는 방법을 찾아볼 것