版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/shiliang97/article/details/101994224
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.
Example:
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/merge-two-sorted-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) {
if(l1==NULL){
return l2;
}
if(l2==NULL){
return l1;
}
ListNode* p;
ListNode* head;
ListNode* p1=l1;
ListNode* p2=l2;
if(p1->val<p2->val){
p=p1;
p1=p1->next;
}else{
p=p2;
p2=p2->next;
}
head=p;
while(p1!=NULL&&p2!=NULL)
{
if(p1->val<p2->val){
p->next=p1;
p1=p1->next;
p=p->next;
}else{
p->next=p2;
p2=p2->next;
p=p->next;
}
}if(p1!=NULL){
p->next=p1;
}else{
p->next=p2;
}
return head;
}
};