题目:
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.
Example:
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#include<iostream>
class Solution {
public:
ListNode* mergeTwoLists(ListNode* left, ListNode* right) {
ListNode* start = NULL;
ListNode* result = NULL;
while(left != NULL && right != NULL) {
if (left->val <= right->val) {
ListNode* temp = new ListNode(left->val);
if (result != NULL) {
result->next = temp;
result = temp;
} else {
start = temp;
result = temp;
}
left = left->next;
} else {
ListNode* temp = new ListNode(right->val);
if (result != NULL) {
result->next = temp;
result = temp;
} else {
start = temp;
result = temp;
}
right = right->next;
}
}
if (left == NULL && right != NULL) {
while(right != NULL) {
ListNode* temp = new ListNode(right->val);
if (result != NULL) {
result->next = temp;
result = temp;
} else {
start = temp;
result = temp;
}
right = right->next;
}
}
if (left != NULL && right == NULL) {
while(left != NULL) {
ListNode* temp = new ListNode(left->val);
if (result != NULL) {
result->next = temp;
result = temp;
} else {
start = temp;
result = temp;
}
left = left->next;
}
}
return start;
}
};