21.Merge Two Sorted Lists
Opened this issue · 0 comments
niuworld commented
Question:
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 *preheader = new ListNode(0), *po = preheader;
if ( l1 == NULL ) return l2;
if ( l2 == NULL ) return l1;
while( l1 && l2 ){
if ( l2 -> val < l1 -> val )
{ //p -> next = new ListNode(l2 -> val);
po -> next = l2;
l2 = l2 -> next;
}
else {
po -> next = l1;
l1 = l1 -> next;
}
po = po -> next;
}
if ( l1 ) po -> next = l1;
if ( l2 ) po -> next = l2;
return preheader -> next;
}
};