Regarding finding the middle element of linked list

后端 未结 5 1615
轮回少年
轮回少年 2021-02-04 20:19

I am following the below approach to calculate the middle element from the linked list , but I want is there any built in method or any other approach which can als

5条回答
  •  后悔当初
    2021-02-04 21:03

    Solution for this question:

    • Use two indexes, first and second, both initialized to 0
    • Increment first by 1 and second by 2 * first
    • Set value of first to middle
    • Loop will execute until value of second is less than list size

    Here is code snippet for getting middle element of list or linked list:

    private int getMiddle(LinkedList list) {
    
       int middle = 0;
       int size = list.size();
    
       for (int i = 0, j = 0; j < size; j = i * 2) {
           middle = i++;
       }
    
       return middle;
    }
    
    LinkedList list = new LinkedList<>();
    list.add("1");
    list.add("2");
    list.add("3");
    list.add("4");
    list.add("5");
    list.add("6");
    list.add("7");
    int middle = getMiddle(list);
    System.out.println(list.get(middle));
    

提交回复
热议问题