我试图找到一种方法来按已输入的姓氏对这个单链表进行排序。我想我可能会尝试冒泡排序,但我在通过第二个元素遍历列表并进行比较时遇到问题。该列表现在仅包含 3 个名称作为控制台条目,但完成后它应该有 10 个名称。任何帮助将不胜感激。
package LinkedList;
import java.util.*;
class SLinkedList
{
public String data1;
public String data2;
public SLinkedList next;
public SLinkedList()
{
data1 = "";
data2 = "";
next = null;
}
public SLinkedList(String value1, String value2)
{
data1 = value1;
data2 = value2;
next = null;
}
public SLinkedList InsertNext(String value1, String value2)
{
SLinkedList node = new SLinkedList(value1, value2);
if(this.next == null)
{
// Easy to handle
node.next = null; // already set in constructor
this.next = node;
}
else
{
// Insert in the middle
SLinkedList temp = this.next;
node.next = temp;
this.next = node;
}
return node;
}
public int DeleteNext()
{
if(next == null)
return 0;
SLinkedList node = this.next;
this.next = this.next.next; // can be NULL here
node = null;
return 1;
}
public void Traverse(SLinkedList node)
{
if(node == null)
node = this;
System.out.println("\nTraversing in Forward Direction\n");
while(node != null)
{
System.out.println(node.data1 + " " + node.data2);
node = node.next;
}
}
public void bubbleSort(SLinkedList node) {
if(node == null)
node = this;
String current;
String second;
String temp;
System.out.println("Attemptint to sort...");
while(node != null)
{
current = node.data2;
node = node.next;
second = node.data2;
System.out.println(current + " " + second);
if(current.compareTo(second) < 0) {
System.out.println("greater than zero");
}
node = null;
//node = node.next;
}
}
public static void main(String[] args)
{
String firstName;
String lastName;
Scanner sc = new Scanner(System.in);
System.out.print("Enter names in the format of: 'Ed King' with"
+ " a single space in between.");
firstName = sc.next();
lastName = sc.next();
SLinkedList node1 = new SLinkedList(firstName, lastName);
System.out.print("Enter second name: ");
firstName = sc.next();
lastName = sc.next();
SLinkedList node2 = node1.InsertNext(firstName, lastName);
System.out.print("Enter third name: ");
firstName = sc.next();
lastName = sc.next();
SLinkedList node3 = node2.InsertNext(firstName, lastName);
node1.bubbleSort(null);
}
}