【剑指Offer 25】合并两个排序的链表

/**
 * 剑指 Offer 25. 合并两个排序的链表
 * https://leetcode.cn/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof/
 * */
public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0); // 哨兵
        ListNode node = head;
        ListNode node1 = l1;
        ListNode node2 = l2;
        // 合并两个链表的结点
        while (node1 != null && node2 != null) {
            if (node1.val < node2.val) {
                node.next = node1;
                node1 = node1.next;
            } else {
                node.next = node2;
                node2 = node2.next;
            }
            node = node.next;
        }
        // 处理剩余结点
        if (node1 != null) {
            node.next = node1;
        }
        if (node2 != null) {
            node.next = node2;
        }
        return head.next;
    }
}
posted @ 2022-06-26 23:20  廖子博  阅读(16)  评论(0编辑  收藏  举报