leetcode-21-链表题-合并两个有序链表 发表于 2020-03-07 | 分类于 数据结构与算法 题目 解法1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253/** * 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) return NULL; if(!l1) return l2; if(!l2) return l1; if(l1->val <= l2->val){ l1->next = mergeTwoLists(l1->next, l2); return l1; }else{ l2->next = mergeTwoLists(l1, l2->next); return l2; } }};// 迭代class Solution {public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if(!l1 && !l2) return NULL; if(!l1) return l2; if(!l2) return l1; ListNode *res = new ListNode(-1); ListNode *temp = res; while(l1 && l2){ if(l1->val <= l2->val){ temp->next = l1; l1 = l1->next; }else{ temp->next = l2; l2 = l2->next; } temp = temp->next; } temp->next = l1 ? l1 : l2; return res->next; }};