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.
难度系数:
容易
实现
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
ListNode *newnode = NULL;
ListNode *node1 = NULL;
ListNode *node2 = NULL;
if (l1 == NULL)
return l2;
else if (l2 == NULL)
return l1;
else if (l1->val > l2->val) {
newnode = l2;
node1 = l1;
node2 = l2->next;
} else {
newnode = l1;
node1 = l1->next;
node2 = l2;
}
ListNode *node = newnode;
while (true) {
if (node1 == NULL) {
node->next = node2;
break;
}
if (node2 == NULL) {
node->next = node1;
break;
}
if (node1->val > node2->val) {
node->next = node2;
node2 = node2->next;
} else {
node->next = node1;
node1 = node1->next;
}
node = node->next;
}
return newnode;
}