LinkedList Finding Middle Element Using List Count --->Method 1

Linked List Node Creation in Java
package single_linkedlist;

public class Node {

	int data;
	Node next;
	public Node(int data) {
		this.data = data;
	}
}
Linked List Implementation Functions
package single_linkedlist;

public class LinkedList {

	public static int listCount(Node head) {
		int count=1;
		Node currentNode = head;
		while(currentNode.next != null) {
			currentNode = currentNode.next;
			count +=1;
		}
		return count;		
	}
	
	public static void listPrintData(Node head) {
		
		Node currentNode = head;
		while(currentNode.next != null) {
			System.out.print(currentNode.data+" --> ");
			currentNode = currentNode.next;			
		}
		System.out.println(currentNode.data);
			
	}
	
	public static void listPrintMiddleDataModel1(Node head) {
		
		int totalCount = listCount(head);

		int middle = (int)Math.ceil((double)totalCount/2);
		Node currentNode = head;
		int count=1;
		while(currentNode.next != null && count<=middle) {
			
			
			if(count == middle) {
				break;
			}
			count +=1;
			currentNode = currentNode.next;	
		}
		System.out.print(currentNode.data);
			
	}
}
Main Class
package single_linkedlist;

public class Test {

	public static void main(String[] args) {
		Node head = new Node(1);
		Node node2 = new Node(2);
		Node node3 = new Node(3);
		Node node4 = new Node(4);
		Node node5 = new Node(5);
		
		//Assign next node to current node
		
		head.next = node2;
		
		node2.next = node3;
		node3.next = node4;
		node4.next = node5;
		node5.next = null;
		 
		System.out.println("List Count :");
		System.out.println(LinkedList.listCount(head));
		
		System.out.println("List Data :");
		LinkedList.listPrintData(head);
		
		System.out.println("List Middle Data :");
		LinkedList.listPrintMiddleDataModel1(head);
		
		
		
		
	}

}

Comments