22 TOPIC: Mid Point of Linked List
33 (Runner Technique)
44
5- - Approach-I: Calculate length of linked list & Iterate till "length/2".
5+ - Approach-I: Calculate length of linked list & then Iterate till "length/2".
66 So, time = l + l/2
77 Complexity O(N)
88
9- - Approach-II: Runner Technique: we will keep 2 pointers,
10- Slow pointer [It will move by one step]
11- Fast pointer [It will move by two steps]
12-
9+ - Approach-II: With Runner Technique we can calculte mid point in single pass (i.e single iteration)
10+ We will keep 2 pointers,
11+ - Slow pointer [It will move by 1 step]
12+ - Fast pointer [It will move by 2 steps]
13+
14+ Fast 2x --------------------------------> |>
15+ Slow 1x ----------------> |
16+ __________________________________|
17+ Start Mid End
18+
19+ Eg: - For Odd number of nodes
20+ F F F // F: Fast pointer (Speed 2x)
21+ 1 -> 2 -> 3 -> 4 -> 5
22+ S S S // S: Slow Pointer (Speed 1x)
23+ [mid]
24+
25+ - For Even number of nodes
26+ Method 1:
27+ F F F
28+ 1 -> 2 -> 3 -> 4 -> NULL
29+ S S S
30+ [mid]
31+
32+ Method 2: [Start "Fast pointer" 1 position ahead of "Slow pointer"]
33+ F F
34+ 1 -> 2 -> 3 -> 4
35+ S S
36+ [mid]
1337*/
1438
1539
@@ -380,9 +404,10 @@ Node* recursive_reverse(Node *head)
380404}
381405
382406
407+ // Finding the mid point of linked list
383408Node* midpoint (Node *head)
384409{
385- // linked list with 1 or 0 node
410+ // linked list with 0 or 1 node
386411 if (head == NULL or head->next == NULL )
387412 {
388413 return head;
@@ -391,13 +416,13 @@ Node* midpoint(Node *head)
391416 Node *slow = head;
392417 Node *fast = head->next ;
393418
394- while (fast != NULL and fast->next != NULL )
419+ while (fast != NULL and fast->next != NULL ) // checking 2 cases for fast pointer bcz fast takes 2 steps
395420 {
396- fast = fast->next ->next ;
397- slow = slow->next ;
421+ fast = fast->next ->next ; // moving 2 steps
422+ slow = slow->next ; // moving 1 step
398423 }
399424
400- return slow;
425+ return slow; // returning the position where slow pointer stops (i.e mid point)
401426}
402427
403428
@@ -425,12 +450,12 @@ int main()
425450/*
426451OUTPUT:
427452
428- Case 1
453+ Case 1 [For Odd number of nodes in linked list]
429454 Enter Elements [Press -1 to Exit] : 1 2 3 4 5 -1
430455 Linked List : 5 -> 4 -> 3 -> 2 -> 1
431456 Linked List [Midpoint] : 3
432457
433- Case 2
458+ Case 2 [For Even number of nodes in linked list]
434459 Enter Elements [Press -1 to Exit] : 1 2 3 4 -1
435460 Linked List : 4 -> 3 -> 2 -> 1
436461 Linked List [Midpoint] : 3
0 commit comments