题目
:::info 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/merge-two-sorted-lists
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
:::
代码
/**
* 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){
return list2;
}
if(list2 == null){
return list1;
}
ListNode l1 = list1; //链表1指针
ListNode l2 = list2; //链表2指针
ListNode head = new ListNode(0); //建立哨兵结点,当作伪头
ListNode curr = head; //伪头指针
while(l1 != null && l2 != null){ //两个链表指针皆不为空
if(l1.val < l2.val){
ListNode newNode = new ListNode(l1.val);
curr.next = newNode;
l1 = l1.next;
curr = curr.next;
}else{
ListNode newNode = new ListNode(l2.val);
curr.next = newNode;
l2 = l2.next;
curr = curr.next;
}
}
if(l1 == null){ //此时两链表必有其一为空
curr.next = l2;
}else{
curr.next = l1;
}
return head.next;
}
}