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
Solution for this question:
first
and second
, both initialized to 0first
by 1 and second
by 2 * first
first
to middlesecond
is less than list sizeHere 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));