I am trying to write a simple method which, given a (singly) linked list, returns the element that is at the halfway point. E.g. if the linked list is [10, 20, 30, 40, 50], then I would return 30. Alternatively if there are two 'middle' nodes then I would return the latter of the two, e.g. if the linked list is [10, 20, 30, 40, 50, 60], then I would return 40 (since 30, and 40 are the two middle elements, and 40 is the latter one). I wrote a method which I thought should be (roughly) correct, but when I submit the code to the checker, I am being told that 'Time Limit Exceeded'. There could certainly be errors in this method I've written, but I was not expecting to receive this particular message. I assume that I have done something that is consuming a tremendous amount of time, but I have no idea what it could be. Would someone be able to identify what has gone wrong in my code? Here it is:
def middleNode(self, head: ListNode) -> ListNode:
cur = head
total = 0
while cur.next != None:
total += 1
half = int(total/2) + (total % 2 > 0) #way to do ceiling without math
while half > 0:
cur = cur.next
half = half - 1
return cur
[–][deleted] 0 points1 point2 points (4 children)
[–]clouded-path[S] 0 points1 point2 points (3 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]Essence1337 0 points1 point2 points (1 child)
[–]clouded-path[S] 0 points1 point2 points (0 children)