赞
踩
合并有序链表核心思路:
双指针:分别遍历两个链表,然后链到总的链表上。
模板:
ListNode head = new ListNode(-1);
ListNode prev = head;
while (list1 != null && list2 != null) {
if (list1.val <= list2.val) {
prev.next = list1;
list1 = list1.next;
} else {
prev.next = list2;
list2 = list2.next;
}
prev=prev.next;
}
prev.next=(list1==null)?list2:list1;
return head.next;
1.输入两个递增的链表,单个链表的长度为n,合并这两个链表并使新链表中的节点仍然是递增排序的。OJ链接
public ListNode Merge(ListNode list1, ListNode list2) { ListNode head = new ListNode(-1); ListNode prev = head; while (list1 != null && list2 != null) { if (list1.val <= list2.val) { prev.next = list1; list1 = list1.next; } else { prev.next = list2; list2 = list2.next; } prev=prev.next; } prev.next=(list1==null)?list2:list1; return head.next; }
2.合并 k 个升序的链表并将结果作为一个升序的链表返回其头节点。OJ链接
int mid = left + (right - left) /2;
可以通过,但是int mid = left + (right - left)>>1;
没办法通过,原因未知,以后再说。public ListNode mergeKLists(ArrayList<ListNode> lists) { return divideMergeLists(lists,0,lists.size()-1); } private ListNode divideMergeLists(ArrayList<ListNode> lists, int left,int right) { if (left > right) { return null; } else if (left == right) { return lists.get(left); } int mid = left + (right - left) /2; return Merge(divideMergeLists(lists, left, mid), divideMergeLists(lists, mid+1, right)); } private ListNode Merge(ListNode list1, ListNode list2) { ListNode head = new ListNode(-1); ListNode prev = head; while (list1 != null && list2 != null) { if (list1.val <= list2.val) { prev.next = list1; list1 = list1.next; } else { prev.next = list2; list2 = list2.next; } prev = prev.next; } prev.next = (list1 == null) ? list2 : list1; return head.next; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。