【题目描述】
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.
【思路】
经典链表题,注意p,q的初始化。
【代码】
/**
* 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 *p,*q;
ListNode *tmp,*head;
if(l1==NULL&&l2==NULL) return NULL;
if(l1==NULL) return l2;
if(l2==NULL) return l1;
p=l1;
q=l2;
if(p->val>q->val){
head=q;
q=q->next;
}
else{
head=p;
p=p->next;
}
tmp=head;
while(p!=NULL&&q!=NULL){
if(p->val>q->val){
tmp->next=q;
tmp=q;
q=q->next;
}
else{
tmp->next=p;
tmp=p;
p=p->next;
}
}
if(p!=NULL){
while(p!=NULL){
tmp->next=p;
tmp=p;
p=p->next;
}
}
if(q!=NULL){
while(q!=NULL){
tmp->next=q;
tmp=q;
q=q->next;
}
}
return head;
}
};