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
解题思路:双指针法;
C++
/**
* 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* head,*temp,*p,*q;
head=new ListNode(0);
temp=head;
p=l1;q=l2;
while(p!=NULL&&q!=NULL){
if(p->val<=q->val){
temp->next=p;
temp=temp->next;
p=p->next;
}
else{
temp->next=q;
temp=temp->next;
q=q->next;
}
}
if(p!=NULL)
temp->next=p;
if(q!=NULL)
temp->next=q;
return head->next;
}
};
Python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
p, q, ans = l1, l2, ListNode(0)
r = ans
while p and q:
if p.val > q.val:
p, q = q, p
r.next = p
p, r = p.next, r.next
if q:
r.next = q
else:
r.next = p
return ans.next