其他分享
首页 > 其他分享> > 【剑指Offer 25】合并两个排序的链表

【剑指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;
    }
}

标签:node,25,null,ListNode,Offer,next,链表,node1,node2
来源: https://www.cnblogs.com/liaozibo/p/offer-25.html