21 合併兩個有序連結串列 merge two sorted lists &&23 合併k個有序連結串列 merge k sorted lists
阿新 • • 發佈:2018-12-19
1.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode temp=new ListNode(0); ListNode firstNode=temp; while(l1!=null && l2!=null){ if(l1.val>l2.val){ temp.next=l2; l2=l2.next; temp=temp.next; } else{ temp.next=l1; l1=l1.next; temp=temp.next; } } //說明l1或者l2為空 while(l1!=null){ temp.next=l1; l1=l1.next; temp=temp.next; } while(l2!=null){ temp.next=l2; l2=l2.next; temp=temp.next; } return firstNode.next; } }
2.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode mergeKLists(ListNode[] lists) { if (lists == null || lists.length == 0) return null; return MSort(lists, 0, lists.length - 1); } public ListNode MSort(ListNode[] lists, int low, int high) { if (low < high) { int mid = (low + high) / 2; ListNode leftlist = MSort(lists, low, mid); ListNode rightlist = MSort(lists, mid + 1, high); return mergeTwoLists(leftlist, rightlist); } // 如果相等,只有一個元素,返回即可 return lists[low]; } // 遞迴合併連結串列 public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode res = null; if (l1 == null) return l2; if (l2 == null) return l1; if (l1.val <= l2.val) { res = l1; l1.next = mergeTwoLists(l1.next, l2); } else { res = l2; l2.next = mergeTwoLists(l1, l2.next); } return res; } }