Merge Two Sorted Lists

来源:互联网 发布:网络金融最初发展阶段 编辑:程序博客网 时间:2024/06/08 05:58

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. * 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;        ListNode *result=NULL;        if(l1->val<l2->val)        {            result=l1;            result->next=mergeTwoLists(l1->next,l2);        }        else        {            result=l2;            result->next=mergeTwoLists(l1,l2->next);        }        return result;    }};


0 0