[LeetCode] 055: Merge Two Sorted Lists

来源:互联网 发布:好看的网络自制剧 编辑:程序博客网 时间:2024/05/18 02:16
[Problem]
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.

[Solution]
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

// at least one of them is NULL
if(NULL == l1)return l2;
if(NULL == l2)return l1;

// both of them are not NULL
ListNode *head = NULL;
if(l1->val < l2->val){
head = new ListNode(l1->val);
l1 = l1->next;
}
else{
head = new ListNode(l2->val);
l2 = l2->next;
}

// merge
ListNode *p = head;
while(l1 != NULL || l2 != NULL){
if(NULL == l1){
p->next = new ListNode(l2->val);
l2 = l2->next;
}
else if(NULL == l2){
p->next = new ListNode(l1->val);
l1 = l1->next;
}
else if(l1->val < l2->val){
p->next = new ListNode(l1->val);
l1 = l1->next;
}
else{
p->next = new ListNode(l2->val);
l2 = l2->next;
}
p = p->next;
}
return head;
}
};
说明:版权所有,转载请注明出处。Coder007的博客