剑指offer打卡Day17:合并两个排序的链表
题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
示例
输入
{1,3,5},{2,4,6}
返回值
{1,2,3,4,5,6}
解析:
-
递归:
-
用剑指OFFER中的解析图表示:
-
递归过程:
- 建立新的头节点res
- res.next 指向 list.val较小的链表
- 递归调用步骤2,返回由新建的头节点建立的新数组
-
实践出真知:
- TALK IS CHEAP,SHOW U MY CODE
- 用下列代码debug运行
Merge_Recursion
一目了然
-
解答:
public class TestDay17 {
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
/**
* 方便debug的toString()
* @return
*/
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
ListNode node = this;
sb.append(node.val);
while (node.next != null) {
sb.append("->");
sb.append(node.next.val);
node = node.next;
}
return String.valueOf(sb);
}
}
// public ListNode Merge_Circulation(ListNode list1, ListNode list2) {
// //新建一个头节点,用来存合并的链表。
// ListNode head = new ListNode(-1);
// head.next = null;
// ListNode root = head;
// while (list1 != null && list2 != null) {
// if (list1.val < list2.val) {
// head.next = list1;
// head = list1;
// list1 = list1.next;
// } else {
// head.next = list2;
// head = list2;
// list2 = list2.next;
// }
// }
// //把未结束的链表连接到合并后的链表尾部
// if (list1 != null) {
// head.next = list1;
// }
// if (list2 != null) {
// head.next = list2;
// }
// return root.next;
// }
public ListNode Merge_Recursion(ListNode list1, ListNode list2) {
if(list1==null)
return list2;
if(list2==null)
return list1;
ListNode res = null;
if(list1.val<list2.val){
res = list1;
res.next = Merge_Recursion(list1.next, list2);
}else{
res = list2;
res.next = Merge_Recursion(list1, list2.next);
}
return res;
}
@Test
public void ttest1() {
ListNode Node1_head = new ListNode(1);
ListNode Node1_1 = new ListNode(3);
ListNode Node1_2 = new ListNode(5);
Node1_head.next = Node1_1;
Node1_1.next = Node1_2;
ListNode Node2_head = new ListNode(2);
ListNode Node2_1 = new ListNode(4);
ListNode Node2_2 = new ListNode(6);
Node2_head.next = Node2_1;
Node2_1.next = Node2_2;
Merge_Recursion(Node1_head, Node2_head);
// Merge_Circulation(Node1_head, Node2_head);
}
}