21 Merge Two Sorted Lists
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 *p1 = l1, *p2 = l2, *dummy = new ListNode(0);
ListNode *p = dummy;
int i1, i2;
while ( p1 != NULL or p2 != NULL ) {
if ( p1 == NULL ) i1 = INT_MAX;
else i1 = p1->val;
if ( p2 == NULL ) i2 = INT_MAX;
else i2 = p2->val;
if ( i1 < i2 ) { p->next = p1; p1 = p1->next;}
else { p->next = p2; p2 = p2->next;}
p = p->next;
}
return dummy->next;
}
};