我们正在为考试做练习,并试图在Java中找到链表的最小值。此算法会不断返回列表的最后一个元素,而不是返回最小值。
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);
}
}
答案 0 :(得分:1)
主要问题在于这部分:
element nxt = this.head.getNext();
nxt= reference;
这不会像您期望的那样更改next
中head
的值。它只是使nxt
变量引用reference
。
您尚未包含Element
类的代码,但是您可能想直接更新next
,例如
this.head.setNext(reference);
也是这一行:
public void MinMax() {
正如您可能期望的那样,并未为您的类定义构造函数,因为名称MinMax
的大小写与类minMax
的大小写不同。构造函数也没有返回类型,因此要解决此问题,请重命名您的类MinMax
(遵循Java命名约定),然后从构造函数定义中删除void
。
答案 1 :(得分:0)
根据您的演示,我只是在本地对其进行了测试并进行了一些修改。
Comparable
接口,就可以使用Comparable
轻松地替换类型(要找到最小值,您必须进行比较); head
作为哨兵,使adding
和deleting
(如果需要删除)更容易; 顺便说一句,在Java中,最好使用 Uppercase 前缀作为类名,因此您的类名element
应该替换为Element
。实际上,您是作为初学者的好方法来封装您的类。
这是代码:
public class HelloWorld {
Node head; // not store any value, just used to link the nodes;
public Comparable findMin() {
if (head == null || head.next == null) {
return null;
}
Comparable min = head.next.value;
Node p = head.next.next;
while(p != null) {
if (min.compareTo(p.value) > 0) min = p.value;
p = p.next;
}
return min;
}
public void add(Node node) {
if (head == null) {
head = new Node(null, node);
} else {
node.next = head.next;
head.next = node;
}
}
public static void main(String... args) {
HelloWorld list = new HelloWorld();
list.add(new Node(5, null));
list.add(new Node(45, null));
list.add(new Node(55, null));
System.out.println(list.findMin().toString());
}
static class Node {
Comparable value;
Node next;
public Node(Comparable theValue, Node theNext) {
this.value = theValue;
this.next = theNext;
}
}
}
输出按预期工作。
5
希望它可以帮助您〜