嘛,这个用递归写的很舒服。
思路就是:比较当前头节点的val,谁的小就用谁的当头节点,接下来拿这个头节点之后的链表和另一个链表继续merge。
代码如下所示:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
if(pHead1==NULL) return pHead2;
if(pHead2==NULL) return pHead1;
ListNode *p=NULL;
if(pHead1->val<=pHead2->val){
pHead1->next=Merge(pHead1->next, pHead2);
return pHead1;
}
else{
pHead2->next=Merge(pHead1, pHead2->next);
return pHead2;
}
}
};