题解 | #合并两个排序的链表#
合并两个排序的链表
https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pHead1 ListNode类
* @param pHead2 ListNode类
* @return ListNode类
*/
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
// write code here
ListNode *head = nullptr;
ListNode *head1 = nullptr;
ListNode *head2 = nullptr;
ListNode* curr = nullptr;
//首先排除有空指针的现象
if(!pHead1 || !pHead2)
{
if(!pHead1)
{
head = pHead2;
}else {
head = pHead1;
}
return head;
}
if(pHead1->val > pHead2->val)
{
head = pHead2;
head1 = pHead1;
head2 = pHead2->next;
curr = head;
}
else {
head = pHead1;
head1 = pHead1->next;
head2 = pHead2;
curr = head;
}
//得到具体的头节点和当前的位置
while(head1 || head2)
{
if(head1 == nullptr)//head1先耗尽
{
//直接连接当前head2的值
curr->next = head2;
break;
}
else if(head2 == nullptr)//head2 先耗尽
{
curr->next = head1;
break;
}
else { //head1 和 head2 都不为空
if(head1->val > head2->val)
{
curr->next = head2;
curr = head2;
head2 = head2->next;
}
else {
curr->next = head1;
curr = head1;
head1 = head1->next;
}
}
}
return head;
}
};
查看19道真题和解析