将两个排序链表合并为一个新的排序链表
样例
给出 1->3->8->11->15->null
,2->null
, 返回 1->2->3->8->11->15->null
。
第一种方法是采用递归,根据两个链表的头节点大小决定合并后链表的头节点,重复此步骤,典型的递归过程。
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param ListNode l1 is the head of the linked list
* @param ListNode l2 is the head of the linked list
* @return: ListNode head of linked list
*/
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
if(l1==NULL){
return l2;
}else if(l2==NULL){
return l1;
}
ListNode *pMergeHead=NULL;
if(l1->val<l2->val){
pMergeHead=l1;
pMergeHead->next=mergeTwoLists(l1->next,l2);
}else{
pMergeHead=l2;
pMergeHead->next=mergeTwoLists(l1,l2->next);
}
return pMergeHead;
}
};
第二种方法是非递归方法,新建指针p作为新链表头结点,依次将两个链表头结点比较,比较结束后将值小的结点从原链表删除,头结点后移,并将此结点连入新链表
class Solution {
public:
/**
* @param ListNode l1 is the head of the linked list
* @param ListNode l2 is the head of the linked list
* @return: ListNode head of linked list
*/
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
if(l1==NULL){
return l2;
}else if(l2==NULL){
return l1;
}
ListNode *pMergeHead=NULL;
//取较小值作头结点
if(l1->val<l2->val){
pMergeHead=l1;
l1=l1->next;
}else{
pMergeHead=l2;
l2=l2->next;
}
ListNode *p=pMergeHead;?
//开始遍历合并
while(l1!=NULL&&l2!=NULL){
if(l1->val<=l2->val){
p->next=l1;
l1=l1->next;
p=p->next;
}
else{
p->next=l2;
l2=l2->next;
p=p->next;
}
}
if(l1!=NULL)
p->next=l1;
if(l2!=NULL)
p->next=l2;
return pMergeHead;
}
};