题目一 使用的方法对链表进行排序
原题: Sort a linked list in O(n log n) time using constant space complexity.
分析: 复杂度为O(n log n) 的排序第一时间想到的就是归并排序,没啥好分析的,算法过程是递归的进行划分,排序,最后进行合并
代码:
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode sortList(ListNode head) {
//O(nlogn)复杂度的排序 那就是归并排序
if(head == null || head.next == null){
return head;
}
//获取链表中间点,使用中间点进行划分链表
ListNode t1 = head;
ListNode t2 = head;
while(t2.next != null && t2.next.next != null){
t1 = t1.next;
t2 = t2.next.next;
}
//t2 为后半段
t2 = t1.next;
//head 为前半段
t1.next = null;
//递归调用排序
ListNode s1 = sortList(head);
ListNode s2 = sortList(t2);
// merge
return merge(s1, s2);
}
public ListNode merge(ListNode s1, ListNode s2){
if (s1 == null && s2 == null){
return null;
}else if(s2 == null){
return s1;
}else if (s1 == null){
return s2;
}
//对两个排好序的链表进行插入排序
ListNode p = new ListNode(0);
ListNode head = p;
while(s1 != null && s2 != null){
if (s1.val < s2.val){
p.next = s1;
s1 = s1.next;
}else{
p.next = s2;
s2 = s2.next;
}
p = p.next;
}
//对于任一链表中的剩余元素,拼接到p之后
if(s1 != null){
p.next = s1;
}else if(s2 != null){
p.next = s2;
}
return head.next;
}
}
题目二: 使用插入法对链表进行排序
原题: Sort a linked list using insertion sort.
分析: 复杂度为O(n log n) 的排序第一时间想到的就是归并排序,没啥好分析的,算法过程是递归的进行划分,排序,最后进行合并
代码: