题目:输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
递归版本:
public ListNode Merge(ListNode list1,ListNode list2) { if (list1 == null) { return list2; } if (list2 == null) { return list1; } ListNode mergeHead = null; if(list1.val>list2.val){ mergeHead=list2; mergeHead.next=Merge(list1,list2.next); }else { mergeHead=list1; mergeHead.next=Merge(list1.next,list2); } return mergeHead; }
非递归版本
public ListNode Merge1(ListNode list1, ListNode list2) { if (list1 == null) { return list2; } if (list2 == null) { return list1; } ListNode mergeHead = new ListNode(0); ListNode temp = mergeHead; while (list1 != null && list2 != null) { if (list1.val < list2.val) { temp.next = list1; list1 = list1.next; } else { temp.next = list2; list2 = list2.next; } temp = temp.next; } temp.next = (list1 == null) ? list2 : list1; return mergeHead.next; }