Skip to content

Commit 915e553

Browse files
Create 876_Middle_of_Linked_List.py
better approach to find middle element of a linked list
1 parent 70321fa commit 915e553

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

876_Middle_of_Linked_List.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
""""
2+
876. Middle of the Linked List
3+
4+
Given the head of a singly linked list, return the middle node of the linked list.
5+
6+
If there are two middle nodes, return the second middle node."""
7+
8+
# Definition for singly-linked list.
9+
# class ListNode:
10+
# def __init__(self, val=0, next=None):
11+
# self.val = val
12+
# self.next = next
13+
class Solution:
14+
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
15+
slow = fast = head
16+
while fast and fast.next:
17+
slow = slow.next
18+
fast = fast.next.next
19+
return slow
20+
21+
22+

0 commit comments

Comments
 (0)