我试图按降序对存储在链表中的多项式进行排序,但是这个算法似乎错过了链表的最后一个节点,所以多项式的最后一个项总是未排序的。有谁知道如何解决这一问题?
Node prev = mult.poly; //mult.poly is a pointer to the first node of the polynomial linked list
Node curr = mult.poly.next;
do{
if (curr.term.degree < prev.term.degree){ //compare degrees
int temp2 = curr.term.degree;
curr.term.degree = prev.term.degree;
prev.term.degree = temp2;
float temp3 = curr.term.coeff;
curr.term.coeff = prev.term.coeff;
prev.term.coeff = temp3;
prev = mult.poly;
curr = mult.poly.next;
}
prev = prev.next;
curr = curr.next;
} while(curr!=null);
return mult;
}
答案 0 :(得分:2)
您已尝试在链接列表上实施bubble-sort。冒泡排序在循环内运行一个循环,你只实现了内循环 - 这就是为什么它不能工作。
示例:
for (int i = 0; i < list.size(); i++) {
Node prev = mult.poly; //mult.poly is a pointer to the first node of the polynomial linked list
Node curr = mult.poly.next;
do {
if (curr.term.degree < prev.term.degree){ //compare degrees
int temp2 = curr.term.degree;
curr.term.degree = prev.term.degree;
prev.term.degree = temp2;
float temp3 = curr.term.coeff;
curr.term.coeff = prev.term.coeff;
prev.term.coeff = temp3;
prev = mult.poly;
curr = mult.poly.next;
}
prev = prev.next;
curr = curr.next;
} while(curr!=null);
}
return mult;
提示:调试按照还原顺序排序的列表上的冒泡排序运行,这样可以更轻松地捕获冒泡排序中的错误。