Merge Two Sorted Lists

来源:互联网 发布:阿里云服务器无法访问 编辑:程序博客网 时间:2024/06/03 20:46

Question

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.

My Solution

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


0 0
原创粉丝点击