将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
struct ListNode *q=l1;
struct ListNode *p=l2;
struct ListNode *l;
struct ListNode *m=(struct ListNode*) malloc (sizeof(struct ListNode));
m->next=NULL;
l=m;
if(q == NULL) return l2;
if(p == NULL) return l1;
while(q &&p){
if(q->val<p->val){
l->next=q;
l=q;
q=q->next;
}
else{
l->next=p;
l=p;
p=p->next;
}
}
if(p){
l->next=p;
}
else{
l->next=q;
}
m=m->next;
return m;
}
这个题比较简单,有三种情况,链表为空,链表等长,或者链表一长一短。
只需要比较数值大小,接着直接改变指针指向即可,代码如是。