我正在做一个图书馆库存系统,所以我应该按字母顺序对 Node 中的名称进行排序。我有书名、作者、isbn 号、副本数和流派,所有这些信息我都存储在一个类中。
我确实为它编写了按字母顺序排序的代码,但它不起作用。 有人可以告诉我我的代码有什么问题吗?
这是我的链表类,包含插入和显示方法:
public class LinkedList
{
Node node = new Node();
static Node head;
public LinkedList()
{
head=null;
}
public Node getHead()
{
return head;
}
public static void addNode(Data data)
{
Node newNode = new Node(data, head);
if (head == null) {
head = newNode;
newNode.setNext(null);
} else {
Node next = head;
Node prev = next;
do {
if (data.name.compareTo(next.data.name) < 0) {
break;
}
prev = next;
next = next.getNext();
} while (next != null);
newNode.setNext(next);
if (data.name.compareTo(next.data.name) < 0) {
head = newNode;
} else prev.setNext(newNode);
}
}
public static String displayNode()
{
Node current = head;
String output = "";
while(current != null){
output+=current.data.toString();
current = current.next;
}
return output;
}
这是我的节点类:
public class Node
{
Data data;
Node next;
public Node()
{
next = null;
}
Node(Data data, Node next)
{
this.data = data;
this.next = next;
}
public Object getData()
{
return data;
}
public Node getNext()
{
return next;
}
public void setNext(Node next)
{
this.next=next;
}
}
这是我的数据类:
public class Data {
LinkedList list;
String name;
String author;
int isbn;
int number;
String genre;
public Data(String name, String author, int isbn, int number, String genre)
{
this.name = name;
this.author = author;
this.isbn = isbn;
this.number = number;
this.genre = genre;
}
public String toString()
{
return("Book Name: "+name+"\nAuthor: "+author+"\nISBN Number: "+isbn+"\nNumber of Copies: "+number+"\nGenre: "+genre+"\n\n");
}
public String getName()
{
return name;
}
这是我用来显示列表的 Iterator 类:
public class DisplayIterator
{
LinkedList list;
static Node current;
static Node newNode;
DisplayIterator(Node newNode)
{
this.newNode = newNode;
current = list.head;
}
public static boolean hasNext()
{
if(current == null){
return false;
}
else if (current.next == null){
return false;
}
return true;
}
public static Node next()
{
if(hasNext()){
current = current.next;
}
return current;
}
public static void remove(){
throw new UnsupportedOperationException("It is read-only.");
}
}
谢谢。
最佳答案
以下代码实现了对链表的基于顺序的插入。这当然假设列表已经排序。做出此假设是安全的,因为在您的界面中将节点添加到链表的唯一方法是通过此方法。
public static void addNode(Data data) {
Node newNode = new Node(data, head);
if (head == null) {
head = newNode;
return;
}
Node current = head;
while (current.next != null && data.name.compareTo(current.data.name) >= 0) {
current = current.next;
}
if (current == head && data.name.compareTo(current.data.name) < 0) {
newNode.next = head;
head = newNode;
}
else {
newNode.next = current.next;
current.next = newNode;
}
JOptionPane.showMessageDialog(null,"Book Information has been added to the inventory.");
}
关于java - 如何使用 Java 按字母顺序对链表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40691259/