您的位置:首页 > 其它

leetcode4.SortLink 及总结 归并排序

2014-05-21 13:43 239 查看
问题:归并一个链表

解决问题类:(定义就不写出了,同5) 参考自:http://blog.csdn.net/lilong_dream/article/details/20284389 http://www.cnblogs.com/shudonghe/p/3302888.html
public class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}

ListNode fast = head;
ListNode slow = head;

while (fast.next != null) {
fast = fast.next.next;
if (fast == null) {
break;
}

slow = slow.next;
}

ListNode right = slow.next;
slow.next = null;

ListNode left = sortList(head);
right = sortList(right);

return mergeTwoLists(left, right);
}

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}

ListNode node = null;
ListNode head = null;

while (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
if (node == null) {
node = l1;
head = node;
} else {
node.next = l1;
node = node.next;
}

l1 = l1.next;
} else {
if (node == null) {
node = l2;
head = node;
} else {
node.next = l2;
node = node.next;
}

l2 = l2.next;
}
}

if (l1 != null) {
node.next = l1;
} else if (l2 != null) {
node.next = l2;
}

return head;
}
}


归并排序代码总结:

package leetcode4.SortLink;

public class MergeSort {

public void mergeSort(int list[],int len){
int array[]=new int[len];//定义临时工作数组
recMergeSort(list, array, 0, len-1);//对数组进行归并排序
}

public void recMergeSort(int list[],int array[],int low,int high){
if(low==high)
return;
else{
int mid=(low+high)/2;
recMergeSort(list, array, 0, mid);
recMergeSort(list, array, mid+1, high);
merge(list,array,low,mid+1,high);
}

}

public void merge(int list[],int array[],int left,int right,int last){
int i=0;
int lowIndex=left;
int mid=right-1;
int n=last-lowIndex+1;

while(left<=mid&&right<=last){//逐个归并
if(list[left]<list[right]){
array[i++]=list[left++];
}else{
array[i++]=list[right++];
}
}

while(left<=mid){//左边剩余归并
array[i++]=list[left++];
}

while(right<=last){//右边剩余归并
array[i++]=list[right++];
}

for(i=0;i<n;i++)
list[lowIndex+i]=array[i];
}

public static void main(String[] args) {
int arr[] = { 2, 8, 14, 46, 3, 12, 89, 43, 5732, 9684, 43, 38 };
MergeSort merger = new MergeSort();
merger.mergeSort(arr, 12);
for (int i = 0; i < 12; i++) {
System.out.print(arr[i] + ",");
}
}
}


总结:对于链表的处理:利用快慢指针将整个链表分为两半,并断开链表,并利用递归的方法继续,最终利用链表合并进行排序

原理图如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: