2
2
TOPIC: Mid Point of Linked List
3
3
(Runner Technique)
4
4
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".
6
6
So, time = l + l/2
7
7
Complexity O(N)
8
8
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]
13
37
*/
14
38
15
39
@@ -380,9 +404,10 @@ Node* recursive_reverse(Node *head)
380
404
}
381
405
382
406
407
+ // Finding the mid point of linked list
383
408
Node* midpoint (Node *head)
384
409
{
385
- // linked list with 1 or 0 node
410
+ // linked list with 0 or 1 node
386
411
if (head == NULL or head->next == NULL )
387
412
{
388
413
return head;
@@ -391,13 +416,13 @@ Node* midpoint(Node *head)
391
416
Node *slow = head;
392
417
Node *fast = head->next ;
393
418
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
395
420
{
396
- fast = fast->next ->next ;
397
- slow = slow->next ;
421
+ fast = fast->next ->next ; // moving 2 steps
422
+ slow = slow->next ; // moving 1 step
398
423
}
399
424
400
- return slow;
425
+ return slow; // returning the position where slow pointer stops (i.e mid point)
401
426
}
402
427
403
428
@@ -425,12 +450,12 @@ int main()
425
450
/*
426
451
OUTPUT:
427
452
428
- Case 1
453
+ Case 1 [For Odd number of nodes in linked list]
429
454
Enter Elements [Press -1 to Exit] : 1 2 3 4 5 -1
430
455
Linked List : 5 -> 4 -> 3 -> 2 -> 1
431
456
Linked List [Midpoint] : 3
432
457
433
- Case 2
458
+ Case 2 [For Even number of nodes in linked list]
434
459
Enter Elements [Press -1 to Exit] : 1 2 3 4 -1
435
460
Linked List : 4 -> 3 -> 2 -> 1
436
461
Linked List [Midpoint] : 3
0 commit comments