题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
新建链表依次存入两个链表中较小的结点
解法一:
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
ListNode res = new ListNode(0);
ListNode result = res;
while(true) {
if(list1 == null) {
res.next = list2;
return result.next;
}
if(list2 == null) {
res.next = list1;
return result.next;
}
if(list1.val < list2.val) {
res.next = list1;
list1 = list1.next;
res = res.next;
}
else {
res.next = list2;
list2 = list2.next;
res = res.next;
}
}
//return result;
}
}