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.
题意:合并两个有序链表。
思路:两个指针边比较边移动。
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode *p, *q, *head;
p = l1;
q = l2;
if (p && q){
if (p->val < q->val){
head = p;
p = p->next;
}
else{
head = q;
q = q->next;
}
}
else if (p == NULL)
return q;
else
return p;
ListNode *tail = head;
while (p && q){
if (p->val < q->val){
tail->next = p;
tail = p;
p = p->next;
}
else{
tail->next = q;
tail = q;
q = q->next;
}
}
if (p == NULL){
tail->next = q;
}
else{
tail->next = p;
}
return head;
}
};