Middle Of Linked List
Given the head node of the singly linked list, return a pointer pointing to the middle of the linked list.
If there are an odd number of elements, return the middle element if there are even elements return the one which is farther from the head node.
For example, let the linked list be 1->2->3->4->null
Since the number of elements in this linked list is 4 so we have 2 middle elements, i.e. 2 and 3, but we return 3 as it is farther from the head node, i.e. 1.
Input Format :
The first line of input contains an integer ‘T’ denoting the number of test cases.
The next ‘2*T’ lines represent the ‘T’ test cases.
The first and only line of each test case contains integers denoting the nodes of the linked list. Each line is guaranteed to have -1 at the end to signify the end of the linked list.
Output Format :
For each test case, return a pointer pointing to the node which is at the middle of the linked list. If no midpoint exists, return a null pointer.
Note :
1.You do not need to print anything, it has already been taken care of. Just implement the given function.
2.For a linked list of size 1, the head node is the midpoint.
3.If no midpoint exists, return a null pointer.
Constraints :
1 <= T <= 50
0 <= N <= 4*10^4
-10^9 <= data <= 10^9
data ≠ -1
Where 'N' is the number of nodes and 'data' is the value of nodes.
Time Limit: 1 sec
AnswerBot
1y
Given the head node of a singly linked list, return a pointer to the middle node. If there are an odd number of elements, return the middle element. If there are even elements, return the one farther ...read more
CodingNinjas
author
2y
Count Nodes Approach
- If we want to know the midpoint of any linked list, it is very easy to do so if we know the number of elements in the linked list.
- We take a pointer ‘p’ and use it to traverse the l...read more
CodingNinjas
author
2y
Two Pointers Approach
- We can find the midpoint of the linked list without finding the number of elements.
- Simply take 2 pointers ‘fast’ and ‘slow’.
- Fast pointer jumps 2 places and slow jumps 1 place.
- Now...read more
Add answer anonymously...
Top Myntra Mern Stack Developer interview questions & answers
Popular interview questions of Mern Stack Developer
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app