Niuke.com High-Frequency Algorithm Question Series-BM12-Single Linked List Sorting
Topic description
describe
See the original title: BM12 singly linked list sorting
Solution 1: Array sorting
First judge that if the linked list is empty or has only one node, no sorting is required, and the original linked list is returned directly.
Otherwise, the extra space is used for sorting, and the process is as follows:
- First traverse the linked list and temporarily store all node values in a List;
- Then, sort the List using library functions (various sorting algorithms can also be used);
- Finally, construct the sorted node value into a new linked list and return it.
Solution 2: Merge Sort
Use recursion to sort the original linked list. The recursive processing process is as follows:
- First of all, it is also necessary to judge that if the linked list is empty or has only one node, no processing is required, and the original linked list is returned directly;
- Then, use the fast and slow pointers to find the midpoint of the linked list;
- Then, recursively call to sort the two linked lists around the midpoint;
- Then, merge the left and right linked lists;
- Finally, return the merged linked list.
code
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Bm012 {
/**
* 数组排序
*
* @param head ListNode类 the head node
* @return ListNode类
*/
public static ListNode sortInList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
List<Integer> nodes = new ArrayList<>();
while (head != null) {
nodes.add(head.val);
head = head.next;
}
// 使用库函数将数组排序
Collections.sort(nodes);
ListNode newHead = new ListNode(-1);
ListNode cur = newHead;
for (Integer val : nodes) {
cur.next = new ListNode(val);
cur = cur.next;
}
return newHead.next;
}
/**
* 归并排序
*
* @param head ListNode类 the head node
* @return ListNode类
*/
public static ListNode sortInList2(ListNode head) {
if (head == null || head.next == null) {
return head;
}
// 使用快慢指针寻找链表的中点位置
ListNode fast = head.next, slow = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode tmp = slow.next;
slow.next = null;
// 递归左右两边进行排序
ListNode left = sortInList(head);
ListNode right = sortInList(tmp);
// 创建新的链表
ListNode newHead = new ListNode(-1);
ListNode cur = newHead;
// 合并left和right链表
while (left != null && right != null) {
if (left.val < right.val) {
cur.next = left;
left = left.next;
} else {
cur.next = right;
right = right.next;
}
cur = cur.next;
}
cur.next = left != null ? left : right;
return newHead.next;
}
public static void main(String[] args) {
ListNode head = ListNode.testCase5();
System.out.println("原链表");
ListNode.print(head);
System.out.println("排序后的链表");
ListNode.print(sortInList(head));
ListNode.print(sortInList2(head));
}
}
$1.01^{365} ≈ 37.7834343329$
$0.99^{365} ≈ 0.02551796445$
Believe in the power of persistence!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。