合并两个列表
21. 合并两个有序链表
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
示例 2:
输入:l1 = [], l2 = []
输出:[]
示例 3:
输入:l1 = [], l2 = [0]
输出:[0]
C语言部分
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
struct ListNode *l=(struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* s=NULL;
if(l1&&l2)
{
if(l1->val>=l2->val)
{
l=l2;
l2=l2->next;
}
else
{
l=l1;
l1=l1->next;
}
s=l;
}
else if(l1==NULL)
return l2;
else if(l2==NULL)
return l1;
while(l1&&l2)
{
if(l1->val<=l2->val)
{
l->next=l1;
l=l1;
l1=l1->next;
}
else
{
l->next=l2;
l=l2;
l2=l2->next;
}
}
if(l1)
l->next=l1;
if(l2)
l->next=l2;
return s;
}
Python部分
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
l=ListNode(-1)
s=l
if l1 and l2:
if l1.val>=l2.val:
l=l2
l2=l2.next
else:
l=l1
l1=l1.next
s=l
elif l1 is None:
return l2
elif l2 is None:
return l1
while l1 and l2:
if l1.val>=l2.val:
l.next=l2
l2=l2.next
else:
l.next=l1
l1=l1.next
l=l.next
if l1 is not None:
l.next=l1
if l2 is not None:
l.next=l2
return s
*Python首秀~~~~熟悉一下语法结构*