合并两个排序的链表(C 牛客网)

解题思路:

(1)依次比较

(2)为解决头指针的问题,先设置一个头指针,后期返回真正的头指针

class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
    	if (pHead1==NULL) return pHead2;
		if (pHead2==NULL) return pHead1;
        ListNode *root = new ListNode(0),*q=root;
        
		while (pHead1 && pHead2) {
        	if (pHead1->val < pHead2->val) {
                q->next = new ListNode(pHead1->val);
                q = q->next;
				pHead1 = pHead1->next;
			} else {
				if (pHead1->val > pHead2->val) {
                    q->next = new ListNode(pHead2->val);
                    q = q->next;
					pHead2 = pHead2->next;
				} else {
                    q->next = new ListNode(pHead1->val);
                    q = q->next;

                    q->next = new ListNode(pHead2->val);
                    q = q->next;

					pHead2 = pHead2->next;
					pHead1 = pHead1->next;
				}
			}
		}
		q->next = pHead1?pHead1:pHead2;
		
		return root->next;
    }
};
发布了302 篇原创文章 · 获赞 277 · 访问量 42万+

猜你喜欢

转载自blog.csdn.net/coolsunxu/article/details/105650509