[LeetCode] Merge Two Sorted Lists

来源:互联网 发布:怎么维护代理商 知乎 编辑:程序博客网 时间:2024/06/17 15:57

题目

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

思路

这道题比较简单,直接上代码。

代码

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {        if(l1 == null)            return l2;        if(l2 == null)            return l1;                    ListNode head = new ListNode(0);        ListNode curr = head;                while(l1 != null && l2 != null) {            int num1 = l1.val;            int num2 = l2.val;            int num3 = 0;                        if (num1 < num2) {                num3 = num1;                l1 = l1.next;            }            else {                num3 = num2;                l2 = l2.next;            }            curr.next = new ListNode(num3);            curr = curr.next;        }                if (l1 != null)            curr.next = l1;        else            curr.next = l2;        return head.next;    }}

0 0