gpt4 book ai didi

java - 链表实现排序方法

转载 作者:行者123 更新时间:2023-12-02 13:24:00 25 4
gpt4 key购买 nike

我制作的链接列表不是来自java集合,我在其中放入了很多方法..我的链接列表的工作方式与原始列表类似,但有一些细微的差别,我的类有一个打印>排序 方法 我的输入是:[5,18,3,10,2] ...或者它可以是字符串输入 ..我想要sort 方法对链表进行排序,因此输出应如下所示:[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;
}
}

heres the full code

最佳答案

尝试使用这种排序方法。

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;
}

}
}
}

关于java - 链表实现排序方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43448006/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com