其他分享
首页 > 其他分享> > 合并两个排序的链表

合并两个排序的链表

作者:互联网

题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

//C++ 递归
class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
        ListNode* cur= NULL;
       if(pHead1==NULL)
           return pHead2;
       if(pHead2==NULL)
           return pHead1;
       if(pHead1->val < pHead2->val){
               cur=pHead1;
               cur->next=Merge(pHead1->next,pHead2);
            }
            else{
                cur=pHead2;
                cur->next=Merge(pHead1,pHead2->next);
            }
           return cur;          
    }
};
/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
//C++ 非递归
class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
           ListNode *vHead=NULL;
           ListNode *cur=NULL;
           vHead=(struct ListNode*)malloc(sizeof(struct ListNode));
           cur=vHead;
           if(pHead1==NULL)
           return pHead2;
            if(pHead2==NULL)
            return pHead1;
            while(pHead1&&pHead2)
            {
                if(pHead1->val > pHead2->val)
                {
                    cur->next=pHead2;
                    pHead2=pHead2->next;
                }
                else
                {
                    cur->next=pHead1;
                    pHead1=pHead1->next;
                }
                cur=cur->next;
            }
            if(pHead1)
                cur->next=pHead1;
            else
                cur->next=pHead2;
            return vHead->next;

            }
};
//java
public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
       ListNode cur = null;
       if(list1==null)
           return list2;
        if(list2==null)
            return list1;
        if(list1.val < list2.val){
            cur = list1;
            cur.next = Merge(list1.next,list2);
        }
        else{
            cur = list2;
            cur.next = Merge(list1,list2.next);
        }
        return cur;
    }
}

标签:ListNode,cur,合并,next,链表,pHead1,pHead2,return,排序
来源: https://blog.csdn.net/liutianying115/article/details/110930794