gpt4 book ai didi

algorithm - 如何按其值对 ListNode(链接)进行排序?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:07:16 26 4
gpt4 key购买 nike

如何在不使用任何库的情况下按值对节点列表进行排序。

例子: * 输入:3->1->5->4->2 * 输出:1->2->3->4->5

列表节点.java

import java.util.List;

public class ListNode {
public int val;
public ListNode next;

public ListNode(int x) {
val = x;
}

public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}

排序链接列表.java

public class SortLinkList {

public static ListNode sortLinkList(ListNode list) {
//TODO:
return list;
}

}```

最佳答案

如果你想要就地排序,你可以只实现冒泡排序:

伪代码:

bool notDone = true
while(notDone)
{
notDone = false;
cur = head;

while(cur.nxt != null)
{
prev = cur;
cur = cur.nxt;

if(cur.val > cur.nxt.val)
{
prev.nxt = cur.nxt;
temp = cur.nxt.nxt;
cur.nxt.nxt = cur;
cur.nxt = temp;
notDone = true;
}
}
}

关于algorithm - 如何按其值对 ListNode(链接)进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55311631/

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