首页 > 学院 > 开发设计 > 正文

Merge Two Sorted Lists

2019-11-15 01:11:08
字体:
来源:转载
供稿:网友
Merge Two Sorted ListsMerge Two Sorted Lists

https://leetcode.com/PRoblems/merge-two-sorted-lists/

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.

算法思想:

连接两个排好序(假设升序,降序类似)的链表,这是一道典型的递归题。比较两个链表的第一个元素,如果l1的第一个node的值要比l2的第一个node的值小,那么新的链表的第一个node就是l1的第一个node,第二个node开始就是l1的第二个node和l2连接起来的list;反之同。

程序清单:
/** * 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;        }                if (l1.val < l2.val) {            l1.next = mergeTwoLists(l1.next, l2);            return l1;        } else {            l2.next = mergeTwoLists(l1, l2.next);            return l2;        }    }}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表