java如何获取单链表来对十六进制数进行排序
嗨,我有这段代码,它将按顺序对字符串列表进行排序,我也可以将数组按升序排序,因为有很多教程可以帮助我。我的问题是用字母对数字进行排序。这可能吗?这是我到目前为止所拥有的
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;
}
}
# 1 楼答案
我认为,您需要使用下面的
Integer
类方法存储一个与String value
对应的额外数据int
数据项其中基数=16。然后可以将其排序为普通整数(以10为基数)
您需要将
Node
类更改为用int
代替String
然后在
getNode(String element)
方法中,执行从int
到^{的十六进制字符串转换现在您可以编辑
insertInOrder()
方法,将其作为简单整数进行比较,><;,==etc而不是value.compareTo
# 2 楼答案
可以对任何类型的
Comparable
元素进行排序如果使用
String
作为值,则将使用字符串的自然顺序对其进行排序。如果需要不同的比较策略,则需要编写Comparator
,并使用它来比较值,而不是直接比较值