合并两个有序链表

it2023-10-20  64

/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) { if(l1==NULL) { return l2; } if(l2==NULL) { return l1; } struct ListNode* head = malloc(sizeof(struct ListNode)); head->val = 0; head->next = NULL; struct ListNode* t = head; while(l1!=NULL && l2!=NULL) { if(l1->val > l2->val) { t->next =l2; l2 = l2->next; t=t->next; } else { t->next = l1; l1 = l1->next; t=t->next; } } if(l2==NULL) { t->next=l1; } else { t->next=l2; } return head->next; }
最新回复(0)