LeetCode : 148. Sort List 排序链表

ゞ 浴缸里的玫瑰 2021-06-24 16:11 524阅读 0赞

试题
Sort a linked list in O(n log n) time using constant space complexity.

Example 1:

Input: 4->2->1->3
Output: 1->2->3->4
Example 2:

Input: -1->5->3->4->0
Output: -1->0->3->4->5

代码
回顾nlog(n)的数组排序算法,一个关键点就是找到中点。在链表中我们需要使用快慢指针来解决。
归并算法如下:

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. class Solution {
  10. public ListNode sortList(ListNode head) {
  11. // 一个节点无需排序
  12. if(head==null || head.next==null) return head;
  13. // 获取中节点,并将链表拆分成两部分
  14. ListNode mid = getMid(head);
  15. // 合并两链表
  16. return mergeLists(sortList(head),sortList(mid));
  17. }
  18. public ListNode getMid(ListNode head){
  19. ListNode slow = head;
  20. ListNode fast = head;
  21. ListNode tail = head;
  22. while(fast!=null && fast.next!=null){
  23. tail = slow;
  24. slow = slow.next;
  25. fast = fast.next.next;
  26. }
  27. tail.next = null;
  28. return slow;
  29. }
  30. public ListNode mergeLists(ListNode l1, ListNode l2){
  31. ListNode dummy = new ListNode(0);
  32. ListNode cur = dummy;
  33. while(l1!=null && l2!=null){
  34. if(l1.val<l2.val){
  35. cur.next = l1;
  36. l1 = l1.next;
  37. }else{
  38. cur.next = l2;
  39. l2 = l2.next;
  40. }
  41. cur = cur.next;
  42. }
  43. if(l1!=null){
  44. cur.next = l1;
  45. }
  46. if(l2!=null){
  47. cur.next = l2;
  48. }
  49. return dummy.next;
  50. }
  51. }

发表评论

表情:
评论列表 (有 0 条评论,524人围观)

还没有评论,来说两句吧...

相关阅读