1、Sort List
链接:https://leetcode.com/problems/sort-list/
思路:使用归并排序。拆分、合并均采用递归方式。
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode slow = head, fast = head, pre = head;
while (fast != null && fast.next != null) {
pre = slow;
slow = slow.next;
fast = fast.next.next;
}
pre.next = null;
return merge(sortList(head), sortList(slow));
}
public ListNode merge(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
if (l1.val < l2.val) {
l1.next = merge(l1.next, l2);
return l1;
} else {
l2.next = merge(l1, l2.next);
return l2;
}
}
2、Insertion Sort List
链接:https://leetcode.com/problems/insertion-sort-list/
思路:新建一个头指针,直接插入排序
public ListNode insertionSortList(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode newhead = new ListNode(-1), temp, pre;
newhead.next = head;
temp = head;
pre = temp.next;
while(pre != null){
if(pre.val > temp.val){
temp = pre;
pre = pre.next;
}else{
ListNode fast = newhead.next;
ListNode low = newhead;
while(fast.val < pre.val){
low = fast;
fast = fast.next;
}
low.next = pre;
temp.next = pre.next;
pre.next = fast;
pre = temp.next;
}
}
return newhead.next;
}
3、Reorder List
链接:https://leetcode.com/problems/reorder-list/
思路:将链表后半段翻转,前半段、后半段交替输出
public void reorderList(ListNode head) {
if(head == null || head.next == null)
return;
ListNode p = head, q = head, r = head;
while(q != null && q.next != null){
r = p;
p = p.next;
q = q.next.next;
}
p = r.next;
while(p.next != null){
q = p.next;
p.next = q.next;
q.next = r.next;
r.next = q;
}
ListNode s,t;
t = r.next;
r.next = null;
s = head;
while(s != null && s.next != null){
p = s.next;
q = t.next;
s.next = t;
t.next = p;
s = p;
t = q;
}
s.next = t;
}