我使链接列表不是来自java集合,我在其中添加了许多方法..我的链接列表与原始列表一样,但是我的类有一个小的差异打印和排序 方法 我的输入是:[5,18,3,10,2] ...或者它可以是字符串输入 ..我想要排序方法对链表进行排序,因此输出应该是这样的:[2,3,5,10,18]或排序后的字符串 这是排序方法代码:
public void sort(){
Node<E> current = head ;
Node<E> current2 = current.next;
E min = head.element;
E temp;
int pos = 0;
for (int i = 0; i < size-1; i++) {
for (int j = 0; j < size; j++) {
if(current2 != null){
if(min.compareTo(current2.element) > 0){
pos = j ;
min = current2.element;
}
current2= current2.next;
}
}
temp = current.element;
current.element = min;
current = current.next;
min = current.element;
current2 = head;
for (int j = 0; j <= pos; j++) {
if(current2 !=null){
if(j==pos){current2.element = temp;}
current2= current2.next;
}
}
current2 = current.next;
}
}
答案 0 :(得分:1)
尝试使用此排序方法。
public void sort()
{
for (int i = size - 1; i >= 1; i--)
{
Node<E> finalNode = head;
Node<E> tempNode = head;
for (int j = 0; j < i; j++)
{
E val1 = head.element;
Node<E> nextnode = head.next;
E val2 = nextnode.element;
if (val1.compareTo(val2))
{
if (head.next.next != null)
{
Node<E> CurrentNext = head.next.next;
nextnode.next = head;
nextnode.next.next = CurrentNext;
if (j == 0)
{
finalNode = nextnode;
}
else
head = nextnode;
for (int l = 1; l < j; l++)
{
tempNode = tempNode.next;
}
if (j != 0)
{
tempNode.next = nextnode;
head = tempNode;
}
}
else if (head.next.next == null)
{
nextnode.next = head;
nextnode.next.next = null;
for (int l = 1; l < j; l++)
{
tempNode = tempNode.next;
}
tempNode.next = nextnode;
nextnode = tempNode;
head = tempNode;
}
}
else
head = tempNode;
head = finalNode;
tempNode = head;
for (int k = 0; k <= j && j < i - 1; k++)
{
head = head.next;
}
}
}
}