Question:How to find middle element of LinkedList in Java in one pass

asked Sep 13, 2013 in JSP by rajesh
edited Sep 12, 2013
0 votes

1 Answer

0 votes


Java program to find middle element of LinkedList in one pass
Here is complete Java program to find middle node of Linked List in Java. Remember LinkedList class here is our custom class and don’t confuse this class with java.util.LinkedList  which is a popular Collection class in Java. In this Java program, our class LinkedList represent a linked list data structure which contains collection of node and has head and tail. Each Node contains data and address part. Main method of LinkedListTest class is used to simulate the problem, where we created Linked List and added few elements on it and then iterate over them to find middle element of Linked List in one pass in Java.
import test.LinkedList.Node;
 * Java program to find middle element of linked list in one pass.
 * In order to find middle element of linked list we need to find length first
 * but since we can only traverse linked list one time, we will use two pointers
 * one which we will increment on each iteration while other which will be
 * incremented every second iteration. so when first pointer will point to the
 * end of linked list, second will be pointing to the middle element of linked list
 * @author
public class LinkedListTest {
    public static void main(String args[]) {
        //creating LinkedList with 5 elements including head
      LinkedList linkedList = new LinkedList();
      LinkedList.Node head = linkedList.head();
      linkedList.add( new LinkedList.Node("1"));
      linkedList.add( new LinkedList.Node("2"));
      linkedList.add( new LinkedList.Node("3"));
      linkedList.add( new LinkedList.Node("4"));
      //finding middle element of LinkedList in single pass
      LinkedList.Node current = head;
      int length = 0;
      LinkedList.Node middle = head;
      while( != null){
          if(length%2 ==0){
              middle =;
          current =;
      if(length%2 == 1){
          middle =;
      System.out.println("length of LinkedList: " + length);
      System.out.println("middle element of LinkedList : " + middle);
class LinkedList{
    private Node head;
    private Node tail;
    public LinkedList(){
        this.head = new Node("head");
        tail = head;
    public Node head(){
        return head;
    public void add(Node node){ = node;
        tail = node;
    public static class Node{
        private Node next;
        private String data;
        public Node(String data){
   = data;
        public String data() {
            return data;
        public void setData(String data) {
   = data;
        public Node next() {
            return next;
        public void setNext(Node next) {
   = next;
        public String toString(){
length of LinkedList: 4
middle element of LinkedList : 2
answered Sep 13, 2013 by rajesh
edited Sep 12, 2013