DESC:
给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
进阶:
你可以在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序吗?
示例 1:
输入:head = [4,2,1,3]
输出:[1,2,3,4]示例 2:
输入:head = [-1,5,3,4,0]
输出:[-1,0,3,4,5]示例 3:
输入:head = []
输出:[]提示:
链表中节点的数目在范围 [0, 5 * 104] 内
-105 <= Node.val <= 105来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
CODE:
JAVA:
/** * 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; } ListNode slow = head; ListNode fast = head.next;//注意这里快指针指向,如果也指向head,碰到1-2-null这种会在slow这里死锁,left一直还是整体 while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } ListNode rightNode = slow.next; slow.next = null; ListNode left = sortList(head); ListNode right = sortList(rightNode); ListNode res = new ListNode(-1); ListNode temp = res; while (left!= null && right != null) { if (left.val <= right.val) { res.next = left; left = left.next; } else { res.next = right; right = right.next; } res = res.next; } if (left != null) { res.next = left; } if (right != null) { res.next = right; } return temp.next; } }
Python
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]: if not head or not head.next: return head slow=head fast=head.next while fast and fast.next: slow = slow.next fast = fast.next.next right = slow.next slow.next = None left = head left = self.sortList(left) right = self.sortList(right) res = ListNode(0) pre = res while left and right: if left.val <= right.val: pre.next = left left = left.next else: pre.next = right right = right.next pre = pre.next if left: pre.next = left if right: pre.next = right return res.next
NOTES:
1. 归并排序
2. 快慢指针平分slow = slow.next;fast = fast.next.next;
3. 注意临时指针记录开始位置