Created
February 16, 2013 22:26
-
-
Save zhoutuo/4968999 to your computer and use it in GitHub Desktop.
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 | |
if(l1 == NULL and l2 == NULL) { | |
return NULL; | |
} else if(l1 == NULL) { | |
return l2; | |
} else if(l2 == NULL) { | |
return l1; | |
} | |
ListNode tmpHead(-1); | |
ListNode* cur = &tmpHead; | |
while(l1 != NULL and l2 != NULL){ | |
if(l1->val > l2->val) { | |
cur->next = l2; | |
l2 = l2->next; | |
} else { | |
cur->next = l1; | |
l1 = l1->next; | |
} | |
cur=cur->next; | |
} | |
if(l1 != NULL) { | |
cur->next = l1; | |
} else { | |
cur->next = l2; | |
} | |
return tmpHead.next; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment