Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.
应该考虑到链表是否为空的情况,代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* new_node = (ListNode*)malloc(sizeof(ListNode));
new_node->next = NULL;
if(l1 == NULL && l2 == NULL){
return NULL;
}else if(l1 == NULL){
return l2;
}else if(l2 == NULL){
return l1;
}
ListNode *p1 = l1,*n1 = l1->next;
ListNode *p2 = l2,*n2 = l2->next;
ListNode *p3 = new_node;
while(p1!=NULL && p2 != NULL){
if(p1->val < p2->val){
p3->next = p1;
p3 = p3->next;
p1 = p1->next;
}else{
p3->next = p2;
p3 = p3->next;
p2 =p2->next;
}
}
if(p1!=NULL) p3->next = p1;
if(p2!=NULL) p3->next = p2;
return new_node->next;
}
};