
主要思路是依次比较两个链表的第一个节点的大小,小的就连接到新链表后面,直到其中一个链表为空后,将剩下的节点一起全部连接新链表最后
cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {
struct ListNode *head = (struct ListNode *)malloc(sizeof(struct ListNode));
head->next = NULL;
struct ListNode *current = head;
while(list1 != NULL && list2 != NULL){
if(list1->val <= list2->val){
current->next = list1;
list1 = list1->next;
}
else{
current->next = list2;
list2 = list2->next;
}
current = current->next;
}
if(list1 != NULL){
current->next = list1;
}
if(list2 != NULL){
current->next = list2;
}
return head->next;
}