在Java中,对链表进行排序可以使用不同的算法,包括选择排序、归并排序、插入排序和快速排序。下面分别介绍这些算法的实现:
选择排序
选择排序的基本思想是每次循环找到链表中最小的元素,并将其移动到链表的前端。
public class SortNodeList {public Node sortList(Node head) {Node curNode = head;while (curNode != null) {Node nextNode = curNode.next;while (nextNode != null) {if (nextNode.data < curNode.data) {// 交换节点int temp = curNode.data;curNode.data = nextNode.data;nextNode.data = temp;}nextNode = nextNode.next;}curNode = curNode.next;}return head;}}
归并排序
归并排序将链表分割成两个子链表,递归地对它们进行排序,然后将它们合并成一个有序的链表。
public class MergeSortList {public Node sortList(Node head) {if (head == null || head.next == null) {return head;}Node slow = head, fast = head.next;while (fast != null && fast.next != null) {slow = slow.next;fast = fast.next.next;}Node mid = slow.next;slow.next = null;Node left = sortList(head);Node right = sortList(mid);return merge(left, right);}private Node merge(Node l1, Node l2) {Node dummy = new Node();Node tail = dummy;while (l1 != null && l2 != null) {if (l1.data < l2.data) {tail.next = l1;l1 = l1.next;} else {tail.next = l2;l2 = l2.next;}tail = tail.next;}tail.next = l1 == null ? l2 : l1;return dummy.next;}}
插入排序
插入排序通过迭代将链表中的每个元素插入到已排序部分的正确位置。
public class InsertionSortList {public ListNode insertionSortList(ListNode head) {ListNode move = head;ListNode emptyHead = new ListNode();emptyHead.next = head;while (move != null && move.next != null) {if (!reInsert(move, emptyHead)) {move = move.next;}}return emptyHead.next;}private boolean reInsert(ListNode node, ListNode emptyHead) {ListNode temp = node.next;node.next = temp.next;while (emptyHead != node) {if (temp.val <= emptyHead.next.val) {temp.next = emptyHead.next;emptyHead.next = temp;} else {break;}emptyHead = emptyHead.next;}return temp.next == null;}}
快速排序
快速排序通过选择一个基准元素,将链表分割成小于基准元素的链表和大于等于基准元素的链表,然后递归地对它们进行排序。

