【发布时间】:2015-07-10 01:00:10
【问题描述】:
我需要维护一个排序的数据结构,从中可以删除和添加项目。为此,我决定选择一个链表。每个数据项都包含一个字母和一些数字,例如: A1480、A1488、B1297、C3119 这些需要按顺序维护。我已经为它编写了代码,它首先在已经排序的链表中找到需要添加新项目的位置,然后将项目添加到正确的位置,从而维护排序的链表。它可以工作,但有些项目放错了位置,我不知道如何修复我的代码。我知道最后一个循环有问题,但我不确定它是什么。
public static void main(String[] args) {
list = new LinkedList<String>();
add("C3138");
add("C3119");
add("A1488");
add("A1480");
add("A1517");
add("B1297");
add("C2597");
add("B1356");
add("C9000");
add("C3517");
add("C3729");
add("C1729");
add("B1729");
}
public static void add(String value) {
// Integer value form the string passed into the method
int valueInt = getInt(value);
// If linked list is empty, add value and return from method
if (list.size() == 0) {
list.add(value);
return;
}
// Compare this item to be added to the first item
int firstNode = getInt(list.get(0));
if (list.get(0).charAt(0) > value.charAt(0)
|| (list.get(0).charAt(0) == value.charAt(0) && firstNode > valueInt)){
list.add(0, value);
return;
}
// Compare this item to the last item
int lastNode = getInt(list.get(list.size() - 1));
if (list.get(list.size() - 1).charAt(0) < value.charAt(0) ||
(list.get(list.size() - 1).charAt(0) == value.charAt(0) && lastNode < valueInt)) {
list.add(list.size(), value);
return;
}
// add the inbetween items
int i = 1;
int tempInt = getInt(list.get(i));
while ((list.get(i).charAt(0) < value.charAt(0)
|| ((list.get(i).charAt(0) == value.charAt(0)) && (valueInt < tempInt)) && i < list.size())) {
tempInt = getInt(list.get(i));
i++;
}
list.add(i, value);
}
public static int getInt(String item) {
return Integer.parseInt(item.replaceAll("\\D", ""));
}
下面的这段代码给了我输出:
[A1480、A1517、A1488、B1729、B1297、B1356、C1729、C3729、C3517、C2597、 C3119、C3138、C9000]
正如您所见,开始和结束之间的某些值放错了位置,但开始和结束值是正确的。请帮忙
【问题讨论】:
-
试试这个 ::
(list.get(i).charAt(0) < value.charAt(0) || ((list.get(i).charAt(0) == value.charAt(0)) && (valueInt > tempInt)) && i < list.size())我之前有点困惑.. :P 只是改变了你的比较符号valueInt > tempInt -
在
LinkedList上使用.get()...如果列表变大的话会很慢...
标签: java sorting insert linked-list