将两个升序丽娜表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例1:输入: l1 = [1,2,4], l2 = [1,3,4]输出: [1,1,2,3,4,4]示例2:输入:l1 = [], l2 = []输出:[]示例3:输入:l1 = [], l2 = [0]输出:[0]
迭代
- 建立一个哑节点
temp,指向新链表的表头节点 - 遍历两个连博鳌,让当前节点
guard指向较小的节点,并使得较小链表往后移一位 - 循环结束时,让
guard指向非空的链表 返回
temp->next:temp只是为了最终的返回做准备/*** 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;// temp是为了最后的返回初始化一个链表struct ListNode *temp = (struct ListNode*)malloc(sizeof(struct ListNode));// 哨兵 作为尾节点持续不断的找当前两个链表头的比较小的节点struct ListNode *guard = temp;while (l1 && l2) {if (l1->val < l2->val) {guard->next = l1;l1 = l1->next;} else {guard->next = l2;l2 = l2->next;}guard = guard->next;}// 最后一定有一个多余的节点没被比较,找到它即可guard->next = (l1==NULL)?l2:l1;return temp->next;}
递归
l1为空那么返回l2,l2为空则返回l1- 比较
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 == 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; } } ```
