-1
我的程序旨在讀取文本文件並將名稱插入到單鏈表中並按字母順序打印名稱。名稱類中有一個compareTo和equals方法,需要在單鏈表中使用類。在singleLinkedList類中,我使用addToList方法來初始創建列表。我設法將每個名字都列入列表中,但我不知道如何使用compareTo方法在單鏈表列類中按字母順序對列表進行排序。這裏是我的代碼: 名稱類:需要幫助按字母順序排序SingleLinkedList
public class Name implements Comparator<Name> {
private String firstName;
private String lastName;
public Name(String firstName, String lastName) {
super();
this.firstName = firstName;
this.lastName = lastName;
}
public String toString(){
return firstName + " " + lastName;
}
public int compareTo(Name name){
return (this.firstName).compareTo(name.firstName);
}
/**
* @return the firstName
*/
public String getFirstName() {
return firstName;
}
/**
* @param firstName the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* @return the lastName
*/
public String getLastName() {
return lastName;
}
/**
* @param lastName the lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
SingleLinkedList類:
public class SingleLinkedList {
private static Node head;
private int listCount;
/**
* No-arg constructor
*/
public SingleLinkedList()
{
}
/**
* adds node to start
* @param name
*/
public void addToStart(Name name)
{
head = new Node(name, head);
listCount++;
}
/**
* adds node to list
* @param name
*/
public void addToList(Name name)
{
if(head != null)
{
Node curr = head;
while(curr.next != null)
{
curr = curr.next;
}
curr.next = new Node(name);
}
else
{
head = new Node(name);
}
listCount++;
}
/**
* Number of nodes in the list
*
* @return list count
*/
public int size()
{
return listCount;
}
public String toString()
{
StringBuilder sb = new StringBuilder();
Node curr = head;
if(curr != null)
{
while(curr.next != null)
{
sb.append(curr.name.toString());
sb.append("\n");
curr = curr.next;
}
sb.append(curr.name.toString());
}
return sb.toString();
}
private class Node
{
private Name name;
private Node next;
public Node(Name name)
{
this.name=name;
next = null;
}
public Node(Name name, Node next)
{
this(name);
this.next = next;
}
}
}
主要驅動力:
public class ClassListDriver {
/**
* @param args
*/
public static void main(String[] args) {
String filename="179ClassList.txt";
Scanner inputStream=null;
SingleLinkedList sll= new SingleLinkedList();
try
{
inputStream=new Scanner(new File(filename));
}
catch(FileNotFoundException e){
System.out.println("Error opening the file.");
System.exit(0);
}
while(inputStream.hasNextLine()){
String[] data=inputStream.nextLine().split(" ");
String firstName=data[0];
String lastName=data[1];
Name name= new Name(firstName,lastName);
sll.addToList(name);
}
System.out.println(sll);
System.out.println(sll.size());
}
}
這裏得到解決http://stackoverflow.com/questions/27410241/sorting-a-list-alphabetically-using-compareto-method?rq=1 – RubioRic