Middle of the Linked List | Linked List Problem

4 years ago Lalit Bhagtani 0

Problem Statement

You have given a singly linked list, return the middle node of a given linked list.

Example 

Linked List

Input :- head = [5, 4, 10, 15, 1]
Output :- 10
Input :- head = [5, 4, 10, 15, 1, 5, 6]
Output :- 15

Solution

Create two variables fast and slow, then move both variables together, fast by two nodes and slow by one node till the fast variable reaches the last or second last node of a linked list. If fast reaches the last node then node at slow variable is the middle node of a linked list otherwise node next to the slow variable is the middle node of a linked list.

Program

public class Main {

	public static void main(String[] args) {
		
		ListNode head = null;
		
		ListNode node = new ListNode(5);
		head = node;		
		node.next = new ListNode(4);
		node = node.next;		
		node.next = new ListNode(10);
		node = node.next;		
		node.next = new ListNode(15);
		node = node.next;		
		node.next = new ListNode(1);
		node = node.next;
		node.next = new ListNode(5);
		node = node.next;
		node.next = new ListNode(6);
		
		Main main = new Main();
		node = main.middleNode(head);
		System.out.print(node.value);
	}
	
	/* Solution */
	public ListNode middleNode(ListNode head) {        
        
        ListNode slow = head;
        ListNode fast = head;
        
        while(fast.next != null && fast.next.next != null){
            fast = fast.next.next;
            slow = slow.next;
        }
        
        if(fast.next == null){
            return slow;
        }else {
            return slow.next;
        }        
    }
	
	/* Definition of Linked List Node */
	public static class ListNode {		
		int value;
		ListNode next;
		
		public ListNode(int value) {
			this.value = value;
		}		
	}
}

Result

15

That’s all for Middle of the Linked List in Java, If you liked it, please share your thoughts in a comments section and share it with others too.