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) {
ListNode *head = NULL, *trav = NULL;
while (l1 != NULL && l2 != NULL) {
if (l1 -> val < l2 -> val) {
if (trav == NULL) {
trav = l1;
head = l1;
} else {
trav -> next = l1;
trav = l1;
}
l1 = l1 -> next;
} else {
if (trav == NULL) {
trav = l2;
head = l2;
} else {
trav -> next = l2;
trav = l2;
}
l2 = l2 -> next;
}
}
if (trav != NULL)
trav -> next = (l1 != NULL ? l1 : l2);
else
head = (l1 != NULL ? l1 : l2);
return head;
}
};
No comments:
Post a Comment