(链表)04-合并两个排序的链表

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
        // 添加头节点
        ListNode root = new ListNode(-1);
        // 定义临时变量
        ListNode temp1 = list1;
        ListNode temp2 = list2;
        ListNode current = root;
        // 拼接新链表
        while(temp1 != null && temp2 != null) {
            if (temp1.val < temp2.val) {
                current.next = temp1;
                temp1 = temp1.next;
            } else {
                current.next = temp2;
                temp2 = temp2.next;
            }
            current = current.next;
        }
        if (temp1 == null) {
            current.next = temp2;
        }
        if (temp2 == null) {
            current.next = temp1;
        }
        // 返回结果
        return root.next;
    }
}

 

posted @ 2023-11-13 23:08  StringBuilder  阅读(15)  评论(0)    收藏  举报