LeetCode - MiddleNode
by ne on 2022-08-26 under Algo/DS/Problems tagged with leetcode
The problem belongs to LeetCode, here is the link to the problem
Following code segment contains the description in the class comments, followed by fully working solution
/**
* Given the head of a singly linked list, return the middle node of the linked list.
*
* If there are two middle nodes, return the second middle node.
*
* Input: head = [1,2,3,4,5]
* Output: [3,4,5]
* Explanation: The middle node of the list is node 3.
*/
public class MiddleNode {
public ListNode middleNode(ListNode head) {
ListNode p1=head;
ListNode p2=head;
while(p2!=null){
p2=p2.next;
if(p2!=null){
p2=p2.next;
}else{
return p1;
}
p1=p1.next;
}
return p1;
}
}