Posts Middle of a Linked List (geeksforgeeks - SDE Sheet)
Post
Cancel

Middle of a Linked List (geeksforgeeks - SDE Sheet)

PROBLEM DESCRIPTION

Given the head of a linked list, the task is to find the middle. For example, the middle of 1-> 2->3->4->5 is 3. If there are two middle nodes (even count), return the second middle. For example, middle of 1->2->3->4->5->6 is 4.

geeksforgeeks

SOLUTION

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {

    int getMiddle(Node head) {

        Node f = head;
        Node s = head;

        while(f != null && f.next != null){
            f = f.next.next;
            s = s.next;
        }

        return s.data;

    }

}
This post is licensed under CC BY 4.0 by the author.