Skip to content

Instantly share code, notes, and snippets.

@pdu
Last active December 13, 2015 19:08
Show Gist options
  • Select an option

  • Save pdu/4960667 to your computer and use it in GitHub Desktop.

Select an option

Save pdu/4960667 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. http://leetcode.com/onlinejudge#question_21
/**
* 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* ret = NULL;
ListNode* cur = NULL;
while (l1 != NULL || l2 != NULL) {
int val = 0;
if (l1 == NULL || (l2 != NULL && l2->val < l1->val)) {
val = l2->val;
l2 = l2->next;
}
else {
val = l1->val;
l1 = l1->next;
}
ListNode* node = new ListNode(val);
if (cur == NULL)
ret = node;
else
cur->next = node;
cur = node;
}
return ret;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment