1.题目:
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
2.代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
struct ListNode *head=(struct ListNode* )malloc(sizeof(struct ListNode));
struct ListNode *p1=l1,*p2=l2,*t=head;
head->next=NULL;
t->next=NULL;
while(p1&&p2){
if(p1->val<=p2->val){
t->next=p1;
t=p1;
p1=p1->next;
}
else{
t->next=p2;
t=p2;
p2=p2->next;
}
}
if(p1)
t->next=p1;
else
t->next=p2;
return head->next;
}
3.知识点:
链表合并