【每日一题】【归并排序】2021年12月20日-148. 排序链表
给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
进阶:
你可以在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序吗?
答案:
/** * 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) { return head == null ? null : mergeSort(head); } public ListNode mergeSort(ListNode head) { if(head.next == null) { return head; } ListNode q = head, p = head, pre = null; while(q != null && q.next != null) { pre = p; p = p.next; q= q.next.next; } pre.next = null; ListNode l = mergeSort(head); ListNode r = mergeSort(p); return merge(l, r); } public ListNode merge(ListNode l, ListNode r) { ListNode dummy = new ListNode(0); ListNode cur = dummy; while(l != null && r != null) { if(l.val <= r.val) { cur.next = l; cur = cur.next; l = l.next; } else { cur.next = r; cur = cur.next; r = r.next; } } if(l != null) { cur.next = l; } if(r != null) { cur.next = r; } return dummy.next; } }