【LeetCode】面试题25. 合并两个排序的链表(JAVA)

原题地址:https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof/

题目描述:
【LeetCode】面试题25. 合并两个排序的链表(JAVA)_第1张图片
解题方案:
设定虚头节点,将两个链表中较小值依次接在后面。

代码:

/**
 * 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) {
        ListNode dummyHead = new ListNode(-1);
        ListNode cur = dummyHead;
        while(l1 != null && l2 != null)
        {
            if(l1.val <= l2.val)
            {
                cur.next = l1;
                l1 = l1.next;
            }
            else
            {
                cur.next = l2;
                l2 = l2.next;
            }
            cur = cur.next;
        }
        if(l1 == null)
            cur.next = l2;
        else
            cur.next = l1;
        return dummyHead.next;
         
    }
}

你可能感兴趣的:(Leetcode)