合并两个排序的链表_牛客题霸_牛客网 (nowcoder.com)
1. 判断两个链表是否有空的 有空返回两外一个
2. 创建虚拟头节点
3. 两者都还有数据的时候 循环遍历
4. 比较大小 将小的放在新建链表中
/*
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 == nullptr) return pHead2;
if(pHead2 == nullptr) return pHead1;
ListNode* newhead = new ListNode(0);
ListNode* cur = newhead;
while(pHead1 && pHead2)
{
if(pHead1->val <= pHead2->val)
{
cur->next = pHead1;
pHead1 = pHead1->next;
}else{
cur->next = pHead2;
pHead2 = pHead2->next;
}
cur = cur->next;
}
if(pHead1 == nullptr) cur->next = pHead2;
if(pHead2 == nullptr) cur->next = pHead1;
return newhead->next;
}
};
- 时间复杂度:O(n),最坏情况遍历两个链表共2∗�2∗n个节点
- 空间复杂度:O(1),无额外辅助空间使用,返回链表使用的是原有节点组装,未开辟空间