输入两个递增的链表,单个链表的长度为n,合并这两个链表并使新链表中的节点仍然是递增排序的。
数据范围: 0 le n le 10000≤n≤1000,-1000 le 节点值 le 1000−1000≤节点值≤1000
要求:空间复杂度 O(1)O(1),时间复杂度 O(n)O(n)
方法一:新建一个哑节点,逐个比较两条链表值的大小还是比较简单的
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
ListNode* dumb = new ListNode(-1);
ListNode* cur = dumb;
while(pHead1 && pHead2){
if(pHead1->val <= pHead2->val){
cur->next = pHead1;
pHead1 = pHead1->next;
}else{
cur->next = pHead2;
pHead2 = pHead2->next;
}
cur=cur->next;
}
cur->next = pHead1 ? pHead1:pHead2;
return dumb->next;
}
};



