剑指offer——合并有序链表

解法一:老实人解法 

/*
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 *newlist = NULL;
        if(pHead1->val < pHead2->val){
            newlist = pHead1;
            pHead1 = pHead1->next;
        }else{
            newlist = pHead2;
            pHead2 = pHead2->next;
        }
        ListNode *end = newlist;
        while(pHead1 != NULL && pHead2 != NULL){
            if(pHead1->val < pHead2->val){
                end->next = pHead1;
                end = pHead1;
                pHead1 = pHead1->next;
            }else{
                end->next = pHead2;
                end = pHead2;
                pHead2 = pHead2->next;
            }
        }
        if(pHead1){
            end->next = pHead1;
        }
        if(pHead2){
            end->next = pHead2;
        }
        return newlist;
    }
};

解法二:递归

public ListNode Merge(ListNode list1,ListNode list2) {
       if(list1 == null){
           return list2;
       }
       if(list2 == null){
           return list1;
       }
       if(list1.val <= list2.val){
           list1.next = Merge(list1.next, list2);
           return list1;
       }else{
           list2.next = Merge(list1, list2.next);
           return list2;
       }       
   }
发布了51 篇原创文章 · 获赞 29 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qwer7512090/article/details/104982316