Merge Two Sorted Lists

来源:互联网 发布:php伪造来路ip 编辑:程序博客网 时间:2024/06/05 20:51

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.

solution: use recursive method.

#include <algorithm>/** * 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 || l2 && l1->val > l2->val) swap(l1, l2);//l1 point to the small pointer.       if(l1) l1->next = mergeTwoLists(l1->next, l2);//if l1 is NULL, end.       return l1;    }};


0 0