I have written this solution, that looks similar to the official one, but I don't understand why it doesn't work.
My solution:
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
arr = []
l = 0
while head:
arr.append(head)
l = 1
head.next
return arr[l//2]
Working solution:
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
arr = [head]
while arr[-1].next:
arr.append(arr[-1].next)
return arr[len(arr) // 2]
Can someone tell me what am I doing wrong?
CodePudding user response:
You're missing the head
reassignment
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
arr = []
curr = head
l = 0
while curr:
arr.append(curr)
l = 1
curr = curr.next
return arr[l//2]