Skip to content

Commit

Permalink
Create middle_linked_list.py
Browse files Browse the repository at this point in the history
finds the middle node of linked list in O(n) time
  • Loading branch information
gabedonnan authored Feb 15, 2023
1 parent 6afb3d8 commit ac0b2e9
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions middle_linked_list.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
temp = head
middle = head
index = 0
prev = 0.5
if temp.next == None:
return temp
while temp != None:
temp = temp.next
if prev % 1 == 0:
middle = middle.next
index += 1
prev += 0.5
return middle

0 comments on commit ac0b2e9

Please sign in to comment.