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

思路

使用一个dummyNode作为新的头节点,使用pHead1,pHead2同时遍历两个链表,将值小的那个节点添加到dummyNode为头节点的末尾,并指针后移。

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
        ListNode dummyNode(0);
        ListNode *dummyHead = &dummyNode;
        while(pHead1 != NULL && pHead2 != NULL)
        {
            ListNode *current = NULL;
            if(pHead1->val < pHead2->val)
            {    
                current = pHead1;
                pHead1 = pHead1->next;
                dummyHead->next = current;
            }
            else
            {
                current = pHead2;
                pHead2 = pHead2->next;
                dummyHead->next = current;
            }
            dummyHead = current;
        }
        if (pHead1 != NULL)
        {
            dummyHead->next = pHead1;
        }
        if (pHead2 != NULL)
        {
            dummyHead->next = pHead2;
        }
        return dummyNode.next;
    }
};
全部评论

相关推荐

今天 17:01
门头沟学院 Java
点赞 评论 收藏
分享
运营3年修炼中接简历辅导:你的科研项目经历里,只写了你的动作,没有写你的思考和成果,不要只写使用什么进行了什么,这等于罗列你的任务,简历是为了突出你的优秀,你在什么样的任务背景下,克服了什么样的困难,针对性地做了哪些事情,最后达成了什么成果(用数据体现你的成果和效率)
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务