Merge Two Sorted Lists
题目:
Merge two sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should be made by splicing together the nodes of the two lists and sorted in ascending order.
分析:
基本题,没有什么特别想说的。
解法:
class Solution {
public:
/**
* @param ListNode l1 is the head of the linked list
* @param ListNode l2 is the head of the linked list
* @return: ListNode head of linked list
*/
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
// write your code here
if (l1 == NULL) {
return l2;
}
if (l2 == NULL) {
return l1;
}
ListNode dummy(0);
ListNode* curr = &dummy;
while (l1 != NULL && l2 != NULL) {
if (l1->val <= l2->val) {
curr->next = l1;
l1 = l1->next;
} else {
curr->next = l2;
l2 = l2->next;
}
curr = curr->next;
}
if (l1 != NULL) {
curr->next = l1;
}
if (l2 != NULL) {
curr->next = l2;
}
return dummy.next;
}
};