|
| 1 | +package Algorithms.sort; |
| 2 | + |
| 3 | +import java.util.LinkedList; |
| 4 | + |
| 5 | +import Algorithms.ListNode; |
| 6 | + |
| 7 | +public class MergeSort_LinkedList { |
| 8 | + public static void main(String[] args) { |
| 9 | + ListNode node1 = new ListNode(0); |
| 10 | + ListNode node2 = new ListNode(15); |
| 11 | + ListNode node3 = new ListNode(6); |
| 12 | + ListNode node4 = new ListNode(9); |
| 13 | + ListNode node5 = new ListNode(4); |
| 14 | + |
| 15 | + node1.next = node2; |
| 16 | + node2.next = node3; |
| 17 | + node3.next = node4; |
| 18 | + node4.next = node5; |
| 19 | + |
| 20 | + System.out.println(node1.toString()); |
| 21 | + sort(node1); |
| 22 | + System.out.println(node1.toString()); |
| 23 | + } |
| 24 | + |
| 25 | + public static ListNode sort(ListNode head) { |
| 26 | + if (head == null) { |
| 27 | + return null; |
| 28 | + } |
| 29 | + |
| 30 | + // 注意一定要加这一行,否则会不断对1个元素无限分下去 |
| 31 | + if (head.next == null) { |
| 32 | + return head; |
| 33 | + } |
| 34 | + |
| 35 | + ListNode mid = findMidPre(head); |
| 36 | + |
| 37 | + // 将list切为2个list. |
| 38 | + ListNode right = mid.next; |
| 39 | + mid.next = null; |
| 40 | + |
| 41 | + //调用将2边分别排序 |
| 42 | + ListNode left = sort(head); |
| 43 | + right = sort(right); |
| 44 | + |
| 45 | + // 将2个已经排序的List Merge在一起 |
| 46 | + return merge(left, right); |
| 47 | + } |
| 48 | + |
| 49 | + public static ListNode merge(ListNode head1, ListNode head2) { |
| 50 | + ListNode dummy = new ListNode(0); |
| 51 | + |
| 52 | + // cur 表示新链的尾部. |
| 53 | + ListNode cur = dummy; |
| 54 | + |
| 55 | + while (head1 != null && head2 != null) { |
| 56 | + // 将2个链中较小的一个接到新链的尾部 |
| 57 | + if (head1.val < head2.val) { |
| 58 | + cur.next = head1; |
| 59 | + head1 = head1.next; |
| 60 | + } else { |
| 61 | + cur.next = head2; |
| 62 | + head2 = head2.next; |
| 63 | + } |
| 64 | + |
| 65 | + // 将扫描指针移动到新链的尾部0 |
| 66 | + cur = cur.next; |
| 67 | + } |
| 68 | + |
| 69 | + // 把未扫描完毕的链接在新链的结尾即可 |
| 70 | + if (head1 != null) { |
| 71 | + cur.next = head1; |
| 72 | + } else { |
| 73 | + cur.next = head2; |
| 74 | + } |
| 75 | + |
| 76 | + // 返回新链的头部 |
| 77 | + return dummy.next; |
| 78 | + } |
| 79 | + |
| 80 | + // 这个函数是寻找Mid的前一个节点, |
| 81 | + // 技巧就是:一开始就将Fast放在head的前一个节点,这样当只有2个节点的时候: |
| 82 | + // 1->2->null |
| 83 | + // slow 会停在1处 ,这样就可以处理只有2个节点的情况. |
| 84 | + public static ListNode findMidPre(ListNode head) { |
| 85 | + if (head == null) { |
| 86 | + return null; |
| 87 | + } |
| 88 | + |
| 89 | + ListNode fast = head.next; |
| 90 | + ListNode slow = head; |
| 91 | + |
| 92 | + if (fast != null && fast.next != null) { |
| 93 | + fast = fast.next.next; |
| 94 | + slow = slow.next; |
| 95 | + } |
| 96 | + |
| 97 | + return slow; |
| 98 | + } |
| 99 | +} |
0 commit comments