我想通過已輸入的姓氏來排序這個單鏈表。我想我可能會嘗試冒泡排序,但我遇到了第二個元素遍歷列表並且進行比較的問題。該列表現在僅包含3個名稱作爲控制檯條目,但完成後應包含10個名稱。任何幫助將不勝感激。按第二個節點元素對單獨鏈接列表排序。 Java
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);
}
}
我不會在這裏發表一個答案,但是對於這種情況,最好使用[Insertion Sort](http://en.wikipedia.org/wiki/Insertion_sort)。 –