描述
输入两个递增的链表,单个链表的长度为n,合并这两个链表并使新链表中的节点仍然是递增排序的。
要求:空间复杂度 O(1),时间复杂度 O(n)
解题思路
初始化:定义cur指向新链表的头结点
操作:
如果l1指向的结点值小于等于l2指向的结点值,则将l1指向的结点值链接到cur的next指针,然后l1指向下一个结点值
否则,让l2指向下一个结点值
循环步骤1,2,直到l1或者l2为nullptr
将l1或者l2剩下的部分链接到cur的后面
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
if(!pHead1) return pHead2;
if(!pHead2) return pHead1;
ListNode* head= new ListNode(-1);
ListNode* cur=head;
while(pHead1!=nullptr && pHead2!=nullptr){//这里必须两个指针都不为零,否则无法比较
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;//将l1或l2剩下的部分接到后面
return head->next;;
}
};
时间复杂度:O(m+n),m,n分别为两个单链表的长度
空间复杂度:O(1)