Skip to content

Commit 4df56ba

Browse files
Create MiddleofLL.py
1 parent 6aa725e commit 4df56ba

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

Linked List/MiddleofLL.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class ListNode:
2+
def __init__(self, value=0, next=None):
3+
self.value = value
4+
self.next = next
5+
6+
def find_middle(head):
7+
# Initialize slow and fast pointers to the head of the linked list
8+
slow_ptr = head
9+
fast_ptr = head
10+
11+
# Traverse the linked list with slow and fast pointers
12+
while fast_ptr is not None and fast_ptr.next is not None:
13+
# Move slow pointer one step at a time
14+
slow_ptr = slow_ptr.next
15+
# Move fast pointer two steps at a time
16+
fast_ptr = fast_ptr.next.next
17+
18+
# When the fast pointer reaches the end, the slow pointer will be at the middle
19+
return slow_ptr
20+
21+
# Create a sample linked list: 1 -> 2 -> 3 -> 4 -> 5
22+
head = ListNode(1)
23+
head.next = ListNode(2)
24+
head.next.next = ListNode(3)
25+
head.next.next.next = ListNode(4)
26+
head.next.next.next.next = ListNode(5)
27+
28+
# Find the middle node of the linked list
29+
middle_node = find_middle(head)
30+
31+
# Print the value of the middle node
32+
print("Middle Node:", middle_node.value) # Output: Middle Node: 3

0 commit comments

Comments
 (0)