Sunday, 26 September 2021

Middle of the Linked List - LeetCode 876

 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.

 

Example 1:

Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The middle node of the list is node 3.

Example 2:

Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.

 

Solution(Only function):

class Solution {

    public ListNode middleNode(ListNode head) {

        //First method using count(Naive method)

//         int count=0;

        

//         ListNode temp=head;

//         ListNode dummy_temp=head;

        

//         while(dummy_temp!=null)

//         {

//             ++count;

//             dummy_temp=dummy_temp.next;

//         }

        

//         count=count/2 + 1;

        

//         while(count>1)

//         {

//             temp=temp.next;

//             --count;

//         }

//         return temp;

      //----------------------------------  

        ListNode slow_ptr=head;

        ListNode fast_ptr=head;

        

        while(fast_ptr!=null && fast_ptr.next!=null)

        {

            slow_ptr=slow_ptr.next;

            fast_ptr=fast_ptr.next.next;

        }

        

        return slow_ptr;

        

    }

}

No comments:

Post a Comment

Random password generator in Java

       Random password generator in Java Source code: mport java.io.*; import java.util.*; public class Main { public static void main(Str...