Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading