题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
思路
- 要注意处理空链表,保证代码的鲁棒性
- 想清楚合并的过程,依次比较两个链表的头结点,把小的放前面。
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
// 考虑链表为空的情况
if (list1 == null) return list2;
else if (list2 == null) return list1;
// 定义合并后的新的头结点
ListNode newHead = null;
// 开始比较两个链表
if (list1.val < list2.val) {
newHead = list1;
newHead.next = Merge(list1.next, list2);
} else {
newHead = list2;
newHead.next = Merge(list1, list2.next);
}
return newHead;
}
}