将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4
解题思路:
1、建立头结点
2、头结点指向两个链表首元素中小元素
3、更改头节点指针,更改被指链表的指针;
4、如果一个链表被被全部加入,把另一个链表直接加在后面
5、释放建立的头结点
实现代码:
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
if(l1 == NULL) {
return l2;
}
else if(l2 == NULL) {
return l1;
}
//创建头节点
struct ListNode* node = (struct ListNode*) malloc (sizeof(struct ListNode));
struct ListNode* cur = node;
struct ListNode* newh;
while(l1 && l2) {
if(l1->val <= l2->val) {
cur->next = l1;
cur = cur->next;
l1 = l1->next;
}
else {
cur->next = l2;
cur = cur->next;
l2 = l2->next;
}
}
if(l1 != NULL) {
cur->next = l1;
}
else if(l2 != NULL){
cur->next = l2;
}
newh = node->next;
free(node);
return newh;
}
运行结果: