执行结果:通过
显示详情
执行用时 :8 ms, 在所有 C++ 提交中击败了98.09%的用户
内存消耗 :9 MB, 在所有 C++ 提交中击败了76.48%的用户
原理:将两个链表中数字提取出来后进行比较,将较小的数输入结果链表中。
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* head = new ListNode(NULL);
ListNode* h = head;
ListNode* p;
ListNode* s;
p = l1;
s = l2;
while(1)
{
if(p == NULL && s == NULL)
{
h->next = nullptr; //表示链表的结尾
head = head->next;
return head;
}
else if(p == NULL && s != NULL)
{
h->next = s;
s = s->next;
h = h->next;
}
else if(p != NULL && s == NULL)
{
h->next = p;
p = p->next;
h = h->next;
}
else
{
if(p->val < s->val)
{
h->next = p;
p = p->next;
h = h->next;
//h->next = s;
//s = s->next;
//h = h->next;
}
else
{
h->next = s;
s = s->next;
h = h->next;
//h->next = p;
//p = p->next;
//h = h->next;
}
}
}
}
};