我必须在链接列表而不是数组上实现 BubbleSort 算法。我是java新手,所以我真的不知道如何将它放入代码中。但我试了一下,这就是我得到的:
单节点.java
public class SinglyNode
{
public Object names;
public SinglyNode next;
public SinglyNode (Object name1)
{
names = name1;
}
public SinglyNode (Object name2, SinglyNode next1)
{
names = name2;
next = next1;
}
Object getObject()
{
return names;
}
SinglyNode getNext()
{
return next;
}
void displayLink()
{
System.out.print("{" + names + "}");
}
}
LinkList.java我认为我的问题出在方法上。我不知道如何实现 BubbleSort,所以它会按升序对对象名称进行排序。
public class LinkList
{
SinglyNode first;
public boolean isEmpty()
{
return (first == null);
}
void insertFirst(Object name1)
{
SinglyNode newNode1 = new SinglyNode(name1);
newNode1.next = first;
first = newNode1;
}
SinglyNode delete(Object name2)
{
SinglyNode temp = first;
first = first.next;
return temp;
}
void display()
{
System.out.print("LIST: \n");
SinglyNode current = first;
while(current != null)
{
current.displayLink(); // print data
current = current.next; // move to next link
}
System.out.println("\n");
}
//////////////////////////////////////////////////////
void bubbleSort()
{
Object n = first;
Object temp = first;
if (na.compareTo(first) < first.compareTo(na))
{
temp = na.compareTo(first);
} else {
temp = first.compareTo(na);
}
System.out.println(temp);
}
private void swap(Object one, Object two)
{
Object temp = one.names;
one.names = two.names;
two.names = temp;
}
}
单链表.java
public class SinglyLinkList
{
public static void main (String args[])
{
LinkList list = new LinkList();
list.insertFirst("Squirtle");
list.insertFirst("Bulbasaur");
list.insertFirst("Charmander");
list.insertFirst("Pichu");
list.insertFirst("Ghastly");
list.insertFirst("Mewtwo");
list.insertFirst("Dialga");
list.display();
list.bubbleSort();
list.display();
}
}