leetcode148.排序链表
思路源自
【力扣hot100】【LeetCode 148】排序链表|归并排序的应用
仿照归并排序
先使用一个快慢指针将链表一分为二,然后进行排序归并
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
} else {
ListNode slow = head, fast = head.next;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode secondPart = slow.next;
slow.next = null;
ListNode firstPart = head;
ListNode sortFirPart = sortList(firstPart);
ListNode sortSecPart = sortList(secondPart);
return sortList(sortFirPart, sortSecPart);
}
}
private ListNode sortList(ListNode l1, ListNode l2) {
ListNode dymmyHead = new ListNode(0, null);
ListNode cur=dymmyHead;
while (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
cur.next=l1;
cur=cur.next;
l1=l1.next;
} else {
cur.next=l2;
cur=cur.next;
l2=l2.next;
}
}
while (l1 != null) {
cur.next=l1;
cur=cur.next;
l1=l1.next;
}
while (l2 != null) {
cur.next=l2;
cur=cur.next;
l2=l2.next;
}
return dymmyHead.next;
}
}