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

合并两个排序的链表

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 == NULL && pHead2 == NULL)
			return NULL;
		if(pHead1 == NULL)
			return pHead2;
		if(pHead2 == NULL)
			return pHead1;
		struct ListNode* p = (struct ListNode*)malloc(sizeof(struct ListNode)); 
    	p->val = -1;
    	struct ListNode *list = p;
		while(pHead1 != NULL && pHead2 != NULL){
			if(pHead1->val <= pHead2->val){
				list->next = pHead1;
				list = list->next;
				pHead1 = pHead1->next;
			}
			else{
				list->next = pHead2;
				list = list->next;
				pHead2 = pHead2->next;
			}
		}
		if(pHead1 == NULL){
			list->next = pHead2;
			return p->next;
		}
		list->next = pHead1;
			return p->next;
    }
};

全部评论

相关推荐

11-15 17:19
湖南大学 Java
成果成果成果果:这是哪个公司的hr,这么离谱吗,我没见过用性别卡技术岗的,身边女性同学拿大厂offer的比比皆是
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务