难以按字母顺序颠倒链表

问题描述 投票:-1回答:3

我在翻转LinkedList时遇到问题。换句话说,我需要它们以z-a顺序排序(与a-z相反)。我试过Collections.reverse但是没有生效?我有以下内容:

import java.io.*;
import java.util.*;
public class pa9Driver {
//create two list
//1st List is of type word class
//2nd list is of type Anagram_Family
public static List<Word> words = new LinkedList<Word>();
public static List<AnagramFamily> familyList = new LinkedList<AnagramFamily>();

//a main method for driver class
public static void main(String[] args) {
//call the generate method to read word from the file
generate_WordList();
//sort the word list
Collections.sort(words);
//generate the anagram family for the word
generate_FamilyList();
//sort the anagram family list      
Collections.sort(familyList, new anagramFamilyComparator());
//reverse the anagram family list
Collections.reverse(familyList);
topFive();
}//main ends

public static void topFive() {
int i;
for(i = 0; i < 15; i++) {
System.out.print(familyList.get(i).getCanonicalForm1() + ", ");
System.out.print(familyList.get(i).getSize() + ": ");
System.out.println(familyList.get(i));
   }
}

//method that read word
public static void generate_WordList() {
File inFile12=new File("words.txt");
Scanner fileRead1=null;
try {
fileRead1 = new Scanner(inFile12);
} catch (Exception exe) {
       exe.printStackTrace();
       System.exit(0);
   }

   //until the file has words read the words
   while(fileRead1.hasNext()) {
       words.add(new Word(fileRead1.next()));
   }
}
//generate the anagram and add it to the current family
public static void generate_FamilyList() {
Iterator<Word> readWord1 = words.iterator();
Word previousWord1 = words.get(0);
familyList.add(new AnagramFamily());
int index1 = 0;
while(readWord1.hasNext()) {
Word currentWord1 = readWord1.next();
if(currentWord1.getCanonicalForm1().equals(previousWord1
.getCanonicalForm1())) {
familyList.get(index1).add(currentWord1);
} else {
index1++;
familyList.add(new AnagramFamily());
familyList.get(index1).add(currentWord1);
  }
previousWord1 = currentWord1;
    }
  }
}

为了方便起见,我只会展示我拥有的前几行代码。目前:

[apers,apres,asper,pares,parse,pears,prase,presa,rapes,reaps,spare,spear]

[警报,祭坛,artels,estral,载荷,速率,盐,板岩,马厩,茎,taler]

预期:

[矛,备用,收割,强奸,普雷萨,prase,梨,解析,削减,asper,apres,apers]

[扬声器,偷窃者,staler,slater,盐,摇铃,诽谤,estral,artels,祭坛,警报]

java
3个回答
0
投票

尝试:

Collections.sort(familyList, Comparator.reverseOrder());

或者,你可以这样做:

Collections.sort(familyList, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o2.compareTo(o1);
            }
        });

//Print list in reverse order
        for(String st : familyList){
            System.out.println(st);
        }

0
投票

看到你的代码,似乎AnagramFamily是一种List,你没有排序。

您需要使用StringComparator对AnagramFamily(字符串列表)进行排序,以获得所需的输出。


-2
投票

我想你可以使用compareTo来做这个动作吗?比较来自可比较

© www.soinside.com 2019 - 2024. All rights reserved.