LeetCode-21. Merge Two Sorted Lists

来源:互联网 发布:极速浏览器 mac 编辑:程序博客网 时间:2024/06/14 15:55

问题:
https://leetcode.com/problems/merge-two-sorted-lists/?tab=Description
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. 合并两个排好序的链表,并返回这个新链表。新链表应该由这两个链表的头部拼接而成。
分析:
使用归并的思想,每次选择值较小的节点接到新链表的后面。
参考C++代码:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {        if(l1==NULL) return l2;        if(l2==NULL) return l1;        if(l1->val > l2->val){            ListNode* tem=l2;            tem->next=mergeTwoLists(l1,l2->next);            return tem;        }        else{            ListNode* tem=l1;            tem->next=mergeTwoLists(l1->next,l2);            return tem;        }    }};
0 0