题目:
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 示例: 输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4
解题思路:
1.递归:
依次加入较小的元素到新的链接中去。
/** * 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){ l2->next = mergeTwoLists(l1,l2->next); return l2; }else{ l1->next = mergeTwoLists(l1->next,l2); return l1; } } };
非递归:
/** * 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 * p1 = l1; ListNode * p2 = l2; ListNode * res = NULL; ListNode * cur = NULL; if(p1 == NULL){ return p2; } if(p2 == NULL){ return p1; } while(p1&&p2){ ListNode * next = NULL; if(p1->val > p2->val){ next = p2; p2 = p2->next; }else{ next = p1; p1 = p1->next; } if(res == NULL){ res = next; cur = next; }else{ cur->next = next; cur = next; } } if(p1){ cur->next = p1; } if(p2){ cur->next = p2; } return res; } }; */ class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if(l1 == NULL && l2 == NULL){ return NULL; } 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; } } };