We are practicing for an exam and are trying to find the minimum value of a linked list in java. This algorithm keeps returning the last element of the list instead of the minimum.
public class minMax {
element head;
public void MinMax(){
this.head = null;
}
public void addElement(element el){
element reference = this.head;
this.head = el;
element nxt = this.head.getNext();
nxt= reference;
}
public int findMin(){
int min = this.head.getValue();
element current = this.head;
while (current != null) {
if(current.getValue() < min){
System.out.println("found min");
min = current.getValue();
}
current = current.getNext();
}
return min;
}
public static void main(String[] args) {
element a = new element(5,null);
element b = new element(55, null);
element c = new element(45, null);
minMax list= new minMax();
list.addElement(a);
list.addElement(b);
list.addElement(c);
int min = list.findMin();
System.out.println(min);
}
}