嗨,我有这段代码,它将按顺序对字符串列表进行排序,我也可以将数组按升序排序,因为有很多教程可以帮助我。我遇到的问题是对附加字母的数字进行排序。这可能吗?这是我到目前为止所拥有的。
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class LinkedList2 {
public static class Node {
public String value;
public Node next;
}
static File dataInpt;
static Scanner inFile;
public static void main(String[] args) throws IOException {
inFile = new Scanner("20\r\n" + "38\r\n" + "5c\r\n" + "2b\r\n" + "54\r\n" + "63\r\n" + "53\r\n" + "43\r\n" + "40\r\n"
+ "14\r\n" + "2a\r\n" + "42\r\n" + "63\r\n" + "63\r\n" + "5c\r\n" + "4c\r\n");
Node first = insertInOrder();
printList(first);
}
public static Node getNode(String element) {
Node temp = new Node();
temp.value = element;
temp.next = null;
return temp;
}
public static void printList(Node head) {
Node ptr; // not pointing anywhere
for (ptr = head; ptr != null; ptr = ptr.next) {
System.out.println(ptr.value);
}
System.out.println();
}
public static Node insertInOrder() {
Node current = getNode(inFile.next());
Node first = current, last = current;
while (inFile.hasNext()) {
if (first != null && current.value.compareTo(first.value) < 0) {
current.next = first;
first = current;
} else if (last != null && current.value.compareTo(last.value) > 0) {
last.next = current;
last = current;
} else {
Node temp = first;
while (current.value.compareTo(temp.value) < 0) {
temp = temp.next;
}
current.next = temp.next;
temp.next = current;
}
current = getNode(inFile.next());
}
return first;
}
}
最佳答案
可以对任何类型的Comparable
元素进行排序。
如果您使用String
作为值,它将使用字符串的自然顺序进行排序。如果您需要不同的比较策略,则需要编写 Comparator
并使用它来比较值,而不是直接比较它们
public static Node insertInOrder(Comparator<String> comparator) {
Node current = getNode(inFile.next());
Node first = current, last = current;
while (inFile.hasNext()) {
if (first != null && comparator.compare(current.value, first.value) < 0) {
current.next = first;
first = current;
} else if (last != null && comparator.compare(current.value, last.value) > 0) {
last.next = current;
last = current;
} else {
Node temp = first;
while (comparator.compare(current.value, temp.value) < 0){
temp = temp.next;
}
current.next = temp.next;
temp.next = current;
}
current = getNode(inFile.next());
}
return first;
}
关于java - 如何获取单链表来对十六进制数字进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34589937/