Skip to content

Instantly share code, notes, and snippets.

@rejoycesong
Last active April 9, 2020 06:52
Show Gist options
  • Save rejoycesong/84895cc8ee48d841f4561b516ba521e4 to your computer and use it in GitHub Desktop.
Save rejoycesong/84895cc8ee48d841f4561b516ba521e4 to your computer and use it in GitHub Desktop.
# Recurse downwards with helper function, counting the number of nodes as you go
# Go back up the call stack, when you're at the middle, return the node.
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
def helper(head, count):
if not head:
return count
rest = helper(head.next, count + 1)
# int(rest / 2) + (rest % 2 > 0) == math.ciel(rest/2)
if type(rest) == int and count == int(rest / 2) + (rest % 2 > 0):
return head
else:
return rest
return helper(head, 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment