21. 合并两个有序链表
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-two-sorted-lists
【提交代码】
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){ struct ListNode *p; struct ListNode *tmp; struct ListNode *dummy; dummy = (struct ListNode *)malloc(sizeof(struct ListNode)); dummy->next = NULL; p = dummy; while( l1 != NULL && l2 != NULL ) { tmp = (struct ListNode *)malloc(sizeof(struct ListNode)); tmp->next = NULL; if( l1->val < l2->val ) { tmp->val = l1->val; l1 = l1->next; } else { tmp->val = l2->val; l2 = l2->next; } p->next = tmp; p = p->next; } while( l1 != NULL ) { tmp = (struct ListNode *)malloc(sizeof(struct ListNode)); tmp->val = l1->val; tmp->next = NULL; p->next = tmp; l1 = l1->next; p = p->next; } while( l2 != NULL ) { tmp = (struct ListNode *)malloc(sizeof(struct ListNode)); tmp->val = l2->val; tmp->next = NULL; p->next = tmp; l2 = l2->next; p = p->next; } return dummy->next; }
【解题思路】
注:实际上和合并两个有序数值的方法是一样的,只不过多了链表节点的增加操作;