编程实现合并两个有序(假定为降序)单链表的函数,输入为两个有序链表的头结点,函数返回合并后新的链表的头节点,
要求:不能另外开辟新的内存存放合并的链表。
递归方式:
/* * 递归方式 */ public LinkNode MergeLinkList(LinkNode head1,LinkNode head2){ if(head1 == null) return head2; if (head2 == null) return head1; LinkNode mergeHead = null; if(head1.value < head2.value){ mergeHead = head1; mergeHead.next = MergeLinkList(head1.next,head2); } else { mergeHead = head2; mergeHead.next = MergeLinkList(head1,head2.next); } return mergeHead; }
非递归方式:
/* * 非递归方式 */ public LinkNode MergeLinkList_1(LinkNode head1,LinkNode head2){ if(head1 == null) return head2; if (head2 == null) return head1; LinkNode mergeHead; LinkNode temp1 = null; LinkNode temp2 = null; if(head1.value < head2.value){ mergeHead = head1; temp1 = head1.next; temp2 = head2; }else{ mergeHead = head2; temp1 = head1; temp2 = head2.next; } LinkNode temp = mergeHead; while(temp1!=null || temp2 !=null){ if(temp1.value < temp2.value){ temp.next = temp1; temp = temp1; temp1 = temp1.next; }else{ temp.next = temp1; temp = temp2; temp2 = temp2.next; } } temp.next = temp1==null ? temp2:temp1; return mergeHead; }