Site icon

Find midpoint / middle node of single linked list in java (example)

Fig 1: Middle node in singly linked list

Algorithm – find middle or mid point of single linked list in java

Example – midpoint/middle node in single linked list using iterative algorithm

Let us apply above algorithm to single linked list to find middle node (example).

Step 1:  

Fig 2: Slow and fast reference in a single linked list

Step 2:

Fig 3: Slow and fast reference traversing single linked list

Step 3:

Fig 4: Slow reference pointing middle node in a single linked list

Time complexity of algorithm is O (n).

Program – find middle or midpoint of single linked in java

1.) FindMiddleNode Class:

package org.learn.Question;

import org.learn.List.Node;

public class FindMiddleNode {
	public static Node findMiddleNode(Node head) {
		if (null == head) {
			System.out.println("Single linked list is empty");
			return null;
		}
		Node slow = head;
		Node fast = head;

		while (fast != null && fast.next != null) {
			slow = slow.next;
			fast = fast.next.next;
		}
		return slow;
	}

	public static void insert(Node head, int data) {
		while (head.next != null)
			head = head.next;
		head.next = new Node(data);
	}

	public static void print(Node head) {
		while (head != null) {
			System.out.printf("%d ", head.data);
			head = head.next;
		}
		System.out.println("");
	}
}

2.) Client Class:

package org.learn.Client;

import org.learn.List.Node;
import org.learn.Question.FindMiddleNode;

public class Client {
	public static void main(String[] args) {
		int[] data = { 1, 2, 3, 4, 5 };
		Node head = new Node(data[0]);

		for (int count = 1; count < data.length; count++)
			FindMiddleNode.insert(head, data[count]);

		System.out.printf("1.) Single linked list is : ");

		FindMiddleNode.print(head);
		Node middle = FindMiddleNode.findMiddleNode(head);
		if (null != middle) {
			System.out.printf("2.) Middle node is at position : %d", middle.data);
		}
	}
}

3.) Node Class:

package org.learn.List;

public class Node {	
	public int data;
	public Node next;
	public Node(int num) {
		this.data = num;
		this.next = null;
	}
}

Output – find middle or midpoint of single linked list in java

1.) Single linked list is : 1 2 3 4 5 
2.) Middle node is at position : 3

Download code – Middle node/midpoint in single linked list java

 

Exit mobile version