递归求解:
public static ListNode mergeTwoListNode(ListNode l1, ListNode l2) {
if (l1 == null || l2 == null) {
return (l1 == null) ? l2 : l1;
}
if (l1.val <= l2.val) {
l1.next = mergeTwoListNode(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoListNode(l1, l2.next);
return l2;
}
}
迭代法:
static ListNode combineListNodeTraverse(ListNode node1, ListNode node2) {
if (node1 == null || node2 == null) {
return node1 == null ? node2 : node1;
}
ListNode head = null;
ListNode tem = null;
while (node1 != null && node2 != null) {
if (node1.val <= node2.val) {
if (head == null) {
head = tem = node1;
} else {
tem.next = node1;
tem = tem.next;
}
node1 = node1.next;
} else {
if (head == null) {
head = tem = node2;
} else {
tem.next = node2;
tem = tem.next;
}
node2 = node2.next;
}
}
if (node1 == null) {
tem.next = node2;
} else {
tem.next = node1;
}
return head;
}
个人才疏学浅、信手涂鸦,更多内容持续更新中,感兴趣的朋友请移步至个人公众号,谢谢支持😜😜......
公众号:wenyixicodedog