题目链接:https://leetcode-cn.com/problems/merge-two-sorted-lists/submissions/
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
我写的:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * struct ListNode *next; 6 * }; 7 */ 8 struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){ 9 if(l1==NULL) return l2; 10 if(l2==NULL) return l1; 11 struct ListNode *l3=(struct ListNode*)malloc(sizeof(struct ListNode));; 12 struct ListNode *pa=l1; 13 struct ListNode *pb=l2; 14 struct ListNode *pc=l3; 15 while(pa&&pb){ 16 if(pa->val<pb->val){ 17 pc->next=pa; 18 pa=pa->next; 19 pc=pc->next; 20 }else{ 21 pc->next=pb; 22 pb=pb->next; 23 pc=pc->next; 24 } 25 } 26 if(pa){ 27 pc->next=pa; 28 } 29 if(pb){ 30 pc->next=pb; 31 } 32 return l3->next; 33 }
%大佬的递归版本
1 struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) { 2 if(l1==NULL) return l2; 3 if(l2==NULL) return l1; 4 if(l1->val < l2->val){ 5 l1->next = mergeTwoLists(l1->next,l2); 6 return l1; 7 }else{ 8 l2->next = mergeTwoLists(l1,l2->next); 9 return l2; 10 } 11 }