在java中对链接列表进行排序的方法
好吧,所以我有这个问题,我所有的信息被发送到链接列表作为对象,这是我想要的。链表将从另一个类中初始化,这个其他类包含LinkedLists的所有方法。有没有一种方法基于数字对链表中的对象进行排序?因为每个元素看起来像这样(“800110简嘿,你在那里”)。睡前在,它们被设置为一个int,字符串,字符串:在java中对链接列表进行排序的方法
//if the command is to RecieveMessage
SinglyLinkedList <String> Jane= new SinglyLinkedList <String>();
int Time;
String Name;
String Message
Time=in.nextInt();
Name=" "+in.next();
Message=in.nextLine();
if(Name.equals(" Jane")) {
//sends message to Janeand increases the number of
//unread messages and notifies Jane
Jane.addLast(Time+Name+Message);
的整数的arent才能,但我有权命令他们,我不知道如何和集合排序心不是允许的。你可以帮我吗? .addlast来自标准链接列表功能。我必须以相同的方式对其他4个用户进行排序,所以如果使用时间戳排序所有这些用户的方法,那将会很棒。 IM也是用这个方法来提取时间:
public static int extractTime(String Sentence) {
int length = Sentence.length();
String result = "";
for (int i = 0; i < length; i++) {
Character character = Sentence.charAt(i);
if (Character.isDigit(character)) {
result += character;
}
}
return Integer.parseInt(result);
}
字符串句子使用for循环在特定的节点是元素:
for(int i=0; i < Jane.size();i++) {
UnreadMessage=Jane.first().toString();
int returnTime= extractTime(UnreadMessage);
}
请帮助,这将帮助了我这么多。
编写一个内部类TimeComp,它实现比较器接口<>。在那里,我们会指定策略到Person对象进行排序,并把它传递到Collections.sort()方法:
class Person{
int time;
String name;
String message;
//Write get and set methods for all member variables
class TimeComp implements Comparator<Person>{
@Override
public int compare(Person p1, Person p2) {
if(p1.getTime() < p2.getTime()){
return 1;
} else {
return -1;
}
}
}
}
List<Person> persons = new LinkedList<Person>();
Collections.sort(persons, TimeComp);
我不想比较两个人之间的时间,1个人(简)有3个与上面相同格式的对象,但时间戳应该按照时间顺序排列 –
如果你得到的节点同时插入到链表之一,你可以使用自底向上合并排序的一种变体,它使用一个小数组(25到32)链表来保存排序列表,其中数组[i]为空或者是对链接列表的引用,其中2^i(2到权力i)节点。每个节点一次合并到一个数组中,并使用合并操作来更新数组。一旦添加了最后一个节点,那么该数组将被合并以形成单个排序列表。 Wiki有一个伪代码示例:
https://en.wikipedia.org/wiki/Merge_sort#Bottom-up_implementation_using_lists
使用自底向上合并排序为这种情况下将有时间复杂性为O(n的log(n)),对为O(n^2)用于插入排序等方法。
排序链接列表效率不高。首先按顺序维护列表比较好,方法是根据顺序选择插入位置。 – EJP
你有没有可能像添加消息之前或消息添加之后我可以调用的一个简短的小方法?因为时间不会按照正确的顺序给出 –