21. Merge Two Sorted Lists
21. Merge Two Sorted Lists
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.
Subscribe to see which companies asked this question
思路:用一个头结点来引导,当链表A和链表B 都还剩的时候,依次将较小的插到答案链表的尾部,最后将剩余的部分置到末尾
</pre><pre code_snippet_id="1751072" snippet_file_name="blog_20160707_3_8839822" name="code" class="cpp">
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode *ans=new ListNode(0);
ListNode *answer=ans;
while(l1 && l2){
if(l1->val<l2->val){
ans->next=l1;
ans=ans->next;
l1=l1->next;
}
else{
ans->next=l2;
l2=l2->next;
ans=ans->next;
}
}
if(l1){
ans->next=l1;
}
if(l2){
ans->next=l2;
}
return answer->next;
}
};
浙公网安备 33010602011771号