🌗 剑指 Offer 25. 合并两个排序的链表
2022年10月10日
- algorithm
🌗 剑指 Offer 25. 合并两个排序的链表
难度: 🌗
问题描述
解法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
// 思路:
//
if(l1 == null) {
return l2;
}
if(l2 == null) {
return l1;
}
ListNode res = new ListNode(-1);
ListNode cur = res;
ListNode a = l1;
ListNode b = l2;
while(a != null && b != null) {
if(a.val <= b.val) {
cur.next = new ListNode(a.val);
a = a.next;
} else {
cur.next = new ListNode(b.val);
b = b.next;
}
cur = cur.next;
}
if(a != null) {
cur.next = a;
}
if(b != null) {
cur.next = b;
}
return res.next;
}
}