标签:pre 有序 ext def ted 递归 app 拼接 有序链表合并
问题描述: 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
迭代:使用双指针分别指向l1和l2,比较出较小值结点
//C /** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){ if(!l1) return l2; if(!l2) return l1; struct ListNode *p1, *p2, *pa, *head; p1 = l1; p2 = l2; if(p1-> val < p2-> val){ head = p1; p1 = p1 -> next; } else { head = p2; p2 = p2 -> next; } pa = head; while(p1 != NULL && p2 != NULL){ if(p1 -> val <= p2 -> val){ pa -> next = p1; pa = p1; p1 = p1 -> next; } else{ pa -> next = p2; pa = p2; p2 = p2 -> next; } } if(p1 != NULL) pa -> next = p1; if(p2 != NULL) pa -> next = p2; return head; } //JS /** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} l1 * @param {ListNode} l2 * @return {ListNode} */ var mergeTwoLists = function(l1, l2) { if(!l1) return l2; if(!l2) return l1; let p = l1, q = l2, head, pa; if(p.val < q.val) { head = p; p = p.next; } else { head = q; q = q.next; } pa = head; while(p && q){ if(p.val < q.val) { pa.next = p; pa = p; p = p.next; } else{ pa.next = q; pa = q; q = q.next; } } if(p) pa.next = p; if(q) pa.next = q; return head; };
递归:
//C struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){ if(l1==NULL){ return l2; } if(l2==NULL){ return l1; } if(l1->val<l2->val || l1->val==l2->val){ l1->next=mergeTwoLists(l1->next,l2);return l1; } else{ l2->next=mergeTwoLists(l1,l2->next);return l2; } } //JS var mergeTwoLists = function(l1, l2) { 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; } };
标签:pre 有序 ext def ted 递归 app 拼接 有序链表合并
原文地址:https://www.cnblogs.com/JesseyWang/p/12968951.html