Home > Back-end >  Implement two ordered list of merger, the merged list still orderly. The list is with the head node,
Implement two ordered list of merger, the merged list still orderly. The list is with the head node,

Time:09-22

/*
Struct ListNode {
Int val.
Struct ListNode * next;
ListNode (int x) :
Val (x), next (NULL) {
}
}; */
The class Solution {
Public:
ListNode * Merge (ListNode * pHead1, ListNode * pHead2)
{
if(! PHead1)
Return pHead2;
if(! PHead2)
Return pHead1;
ListNode * Head=pHead1;//use the first list of head pointer to the new list of head node
P1=pHead1 ListNode * - & gt; next;
ListNode * p2=pHead2 - & gt; next;//p1, p2, respectively, to even have a list of the first node
ListNode * p=Head;
While (p1 & amp; & P2) {
If (p1 - & gt; Val & lt;=p2 - & gt; Val) {
p-> Next=p;
P=p;
P1=p1 - & gt; next;
} else {
p-> Next=p2;
P=p2.
The p2=p2 - & gt; next;
}//else
}//while
p-> Next=p1? P1, p2,

Return the Head;
}
};

CodePudding user response:

Input for the two chains, and output for the combined list, but don't want any space for the output distribution,
Under the condition of invariable, the total number in the list, two linked list data are likely to be modified, if the lock chain table 1 for the output value at this time, may need to exchange head,

ListNode * Head=pHead1;//use the first list of head pointer to the new list of head node, this definition is not very good,
If (p1 - & gt; Val & lt;=p2 - & gt; Return to the pHead1 val)//because, so have to exchange, if can return to pHead2, can not exchange,
STD: : swap (* pHead1, * pHead2);

P1=pHead1 ListNode * - & gt; next;
ListNode * p2=pHead2;//this is not a node, it is the second node,,
ListNode * p=Head;
Need not move back...