题解 | #合并两个排序的链表#

合并两个排序的链表

https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337

递归法:

/*
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 || !pHead2) return pHead1 ? pHead1 : pHead2;
		if(pHead1->val < pHead2->val) {
			pHead1->next = Merge(pHead1->next, pHead2);
			return pHead1;
		} else {
			pHead2->next = Merge(pHead1, pHead2->next);
			return pHead2;
		}
    }
};

头节点双链表法:

/*
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 || !pHead2) return pHead1 ? pHead1 : pHead2;
		ListNode *ret = new ListNode(-1);
		ListNode *cur = ret;
		while(pHead1 && pHead2) {
			ListNode* tmp = pHead1->val < pHead2->val ? pHead1 : pHead2;
			cur->next = tmp;
			if(tmp == pHead1) pHead1 = pHead1->next;
			else pHead2 = pHead2->next;

			cur = cur->next;
		}
		cur->next = pHead1 ? pHead1 : pHead2;

		return ret->next;
    }
};

全部评论

相关推荐

勇敢的联想人前程似锦:如果我是你,身体素质好我会去参军,然后走士兵计划考研211只需要200多分。
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务