【LeetCode】C# 21、Merge Two Sorted Lists

来源:互联网 发布:sql 设置列默认值 编辑:程序博客网 时间:2024/06/06 17:54

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.

合并两个有序的链表成一个有序链表。

思路:只有一个过程,就是判断两个链表当前的值,把小的给结果ListNode,然后进入下一个循环,就能实现整合列表。

/** * Definition for singly-linked list. * public class ListNode { *     public int val; *     public ListNode next; *     public 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 = (l1.val < l2.val) ? l1 : l2;        ListNode nonhead = (l1.val < l2.val) ? l2:l1;        head.next = MergeTwoLists(head.next,nonhead);        return head;    }}