两个不带头结点的有序单列表la和lb合并,合并到la中,并释放lb空间
时间: 2023-03-26 11:01:06 浏览: 130
【PTA数据结构】7-2 两个有序链表序列的合并.txt
可以这样实现:
```
void mergeList(ListNode* &la, ListNode* &lb) {
ListNode* p = la;
ListNode* q = lb;
ListNode* r = nullptr;
if (!p) {
la = lb;
lb = nullptr;
return;
}
if (!q) {
return;
}
if (p->val <= q->val) {
r = p;
p = p->next;
} else {
r = q;
q = q->next;
}
la = r;
while (p && q) {
if (p->val <= q->val) {
r->next = p;
r = p;
p = p->next;
} else {
r->next = q;
r = q;
q = q->next;
}
}
if (p) {
r->next = p;
} else {
r->next = q;
lb = nullptr;
}
}
```
阅读全文