[3]合并两个有序链表
A.迭代法
a.图解
b.源码
/*
* @lc app=leetcode.cn id=21 lang=java
*
* [21] 合并两个有序链表
*/
// @lc code=start
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode res = new ListNode();
ListNode cur = res;
while (list1 != null && list2 != null) {
if (list1.val <= list2.val) {
cur.next = list1;
list1 = list1.next;// 已经确认好一个数,挪到list1的下一个数
} else {
cur.next = list2;
list2 = list2.next;
}
cur = cur.next;// 每一次while循环都确定了一个最小的数,确定好的值留下然后再确定下一个值
}
if (list1 == null) {// list2可能有剩余
cur.next = list2;
}
if (list2 == null) {// list1可能有剩余
cur.next = list1;
}
return res.next;
}
}
// @lc code=end
B.递归法
a.图解
b.源码
/*
* @lc app=leetcode.cn id=21 lang=java
*
* [21] 合并两个有序链表
*/
// @lc code=start
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if (list1 == null || list2 == null) {
return list1 = null ? list2 : list1;
}
if (list1.val <= list2.val) {
list1.next = mergeTwoLists(list1.next, list2);
return list1;
} else {
list2.next = mergeTwoLists(list1, list2.next);
return list2;
}
}
}
// @lc code=end