Skip to content

Commit b77af99

Browse files
Create Middle of the Linked List.py
1 parent 7101623 commit b77af99

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Definition for singly-linked list.
2+
# class ListNode:
3+
# def __init__(self, val=0, next=None):
4+
# self.val = val
5+
# self.next = next
6+
class Solution:
7+
def middleNode(self, head: ListNode) -> ListNode:
8+
'''
9+
curr = head
10+
l = 0
11+
while curr.next is not None:
12+
curr = curr.next
13+
l += 1
14+
curr = head
15+
while l > 0:
16+
curr = curr.next
17+
l -= 2
18+
return curr
19+
'''
20+
# two pointers
21+
slow = fast = head
22+
while fast and fast.next: #fast and fast.next to avoid None type has no attribute next error
23+
slow = slow.next
24+
fast = fast.next.next
25+
return slow

0 commit comments

Comments
 (0)