Skip to content

Instantly share code, notes, and snippets.

@zhoutuo
Created February 16, 2013 22:26
Show Gist options
  • Save zhoutuo/4968999 to your computer and use it in GitHub Desktop.
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.
/**
* 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