难以按字母顺序颠倒链表

时间:2018-03-04 03:42:36

标签: java

我在翻转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,laster,ratels,salter,slater,staler,stelar,talers]

预期:

  

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

     

[taler,stelar,staler,slater,salter,ratels,laster,estral,artels,alters,alert]

2 个答案:

答案 0 :(得分: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);
        }

答案 1 :(得分:0)

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

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