实现Java代码,设计一个函数,其功能为实现单链表中的所有节点按元素值进行排序,同时编制一设计一个函数,其功能为实现单链表中的所有节点按元素值进行排序,同时编制一个主程序,对该函数的功能进行测试。个主程序,对该函数的功能进行测试。
时间: 2023-05-22 21:01:02 浏览: 48
以下是实现单链表中的所有节点按元素值进行排序的 Java 代码:
```java
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode slow = head;
ListNode fast = head.next;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode mid = slow.next;
slow.next = null;
ListNode left = sortList(head);
ListNode right = sortList(mid);
return merge(left, right);
}
private ListNode merge(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode cur = dummy;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
cur.next = l1;
l1 = l1.next;
} else {
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
if (l1 != null) {
cur.next = l1;
}
if (l2 != null) {
cur.next = l2;
}
return dummy.next;
}
}
public class Main {
public static void main(String[] args) {
ListNode head = new ListNode(3);
head.next = new ListNode(1);
head.next.next = new ListNode(4);
head.next.next.next = new ListNode(2);
Solution solution = new Solution();
ListNode sortedList = solution.sortList(head);
while (sortedList != null) {
System.out.print(sortedList.val + " ");
sortedList = sortedList.next;
}
}
}
```
这段代码实现了一个 `sortList` 函数,可以对单链表中的所有节点按元素值进行排序。主程序中创建了一个单链表,然后调用 `sortList` 函数对其进行排序,并输出排序后的结果。