标签:blog http ar java art log 代码 amp ad
此题要求用归并排序排两个链表,基本思想还是分为分割和合并
合并的代码在Merge Two Sorted List里已经讲得很清楚了。所以这里直接给出代码。
public ListNode merge(ListNode l1, ListNode l2) { ListNode helper = new ListNode(0); ListNode runner = helper; while (l1 != null && l2 != null) { if (l1.val < l2.val) { runner.next = l1; l1 = l1.next; runner = runner.next; } else { runner.next = l2; l2 = l2.next; runner = runner.next; } if (l1 != null) runner.next = l1; if (l2 != null) runner.next = l2; } return helper.next; }
数组中判断只有一个元素的方法是if(left==right)
链表中判断只有一个元素的方法是if(head.next==null)
数组中的分割的方法是
int middle = (left + right) / 2; mergeSort(array, left, middle); mergeSort(array, middle + 1, right); merge(array, left, middle, right);
ListNode walker = head; ListNode runner = head; while (runner.next != null && runner.next.next != null) { walker = walker.next; runner = runner.next.next; } ListNode head2 = walker.next; walker.next = null; head = mergeSort(head); head2 = mergeSort(head2); return merge(head, head2);
public ListNode sortList(ListNode head) { if (head == null) return head; return mergeSort(head); } public ListNode mergeSort(ListNode head) { if (head.next == null) return head; ListNode walker = head; ListNode runner = head; while (runner.next != null && runner.next.next != null) { walker = walker.next; runner = runner.next.next; } ListNode head2 = walker.next; walker.next = null; head = mergeSort(head); head2 = mergeSort(head2); return merge(head, head2); } public ListNode merge(ListNode l1, ListNode l2) { ListNode helper = new ListNode(0); ListNode runner = helper; while (l1 != null && l2 != null) { if (l1.val < l2.val) { runner.next = l1; l1 = l1.next; runner = runner.next; } else { runner.next = l2; l2 = l2.next; runner = runner.next; } if (l1 != null) runner.next = l1; if (l2 != null) runner.next = l2; } return helper.next; }
标签:blog http ar java art log 代码 amp ad
原文地址:http://blog.csdn.net/yexiao123098/article/details/40580861