/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode (int x): Val (x), Next (NULL) {}
* };
*/
Class Solution {
Public
listnode* mergetwolists (listnode* L1, listnode* L2) {
Maintain a new list with two pointers to the linked list, and be aware that the head node is not the same as the nodes behind it.
if (l1==null)
return L2;
if (l2==null)
return L1;
listnode*head= null;//Head pointer
Listnode*cur= null;//The point of the current operation
Listnode*p =l1;
Listnode*q =l2;
while (P&&Q)
{if (head = = NULL)
{if (p->val<q->val)
{
head = cur= p;
p= p->next;
Head->next = NULL;
}
Else
{
head = cur = q;
q= q->next;
Head->next = NULL;
}
}
Else
{
if (p->val<q->val)
{
Cur->next= p;
Cur= Cur->next;
p= p->next;
Cur->next = NULL;
}
Else
{
cur->next= Q;
Cur= Cur->next;
q= q->next;
Cur->next = NULL;
}
}
}
if (p!= NULL)
Cur->next= p;
else if (q!= NULL)
Cur->next = q;
return head;
}
};
Merge Sorted Lists