Solving Leet Code "876. Middle of the Linked List", easy level

Question:

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?

Asked By: Jean

||

Answers:

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]
Answered By: azro
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.