Created
April 1, 2017 16:22
-
-
Save s4553711/dd27ea0f2a6daf839a12c04a9c785575 to your computer and use it in GitHub Desktop.
leetcode-21. Pay attention to the h and t linked list pointer
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) { | |
ListNode *h1 = new ListNode(0); | |
ListNode *h2 = new ListNode(0); | |
h1->next = l1; | |
h2->next = l2; | |
ListNode *h = new ListNode(0); | |
ListNode *t = h; | |
while (h1->next != NULL || h2->next != NULL) { | |
if (h1->next == NULL || | |
h2->next != NULL && h1->next->val > h2->next->val) { | |
t->next = h2->next; | |
t = t->next; | |
h2->next = t->next; | |
} else { | |
t->next = h1->next; | |
t = t->next; | |
h1->next = t->next; | |
} | |
} | |
return h->next; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment