我刚刚解决了该问题的第一部分
它只需输入两个排序的列表,然后形成两个列表中最大节点路径的第三个列表
GeeksForGeeks上的问题
我唯一要做的就是获取两个列表之间的开关号(开关不一定是公共节点)。
List MaxSumPath(Node* head1, Node* head2)
{
List l;
Node* temp1 = 0;
Node* temp2 = 0;
Node* temp = 0;
Node* result = 0;
int sum1 = 0;
int sum2 = 0;
while (head1 != 0 || head2 != 0) {
temp1 = head1;
temp2 = head2;
sum1 = sum2 = 0;
while (head1 != 0 && head2 != 0)
{
if (head1->num < head2->num)
{
sum1 += head1->num;
head1 = head1->next;
}
else if (head2->num < head1->num)
{
sum2 += head2->num;
head2 = head2->next;
}
else { /* (head1->num == head2->num)*/
break;
}
}
if (head1 == 0)
{
while(head2 != 0){
sum2 += head2->num;
head2 = head2->next;
}
}
if (head2 == 0)
{
while (head1 != 0){
sum1 += head1->num;
head1 = head1->next;
}
}
if (sum1 >= sum2)
{
if (result == 0) {
result = temp1;
temp = head1;
}
else {
temp->next = temp1;
temp = head1;
}
}
if (sum1 < sum2) {
if(result == 0) {
result = temp2;
temp = head2;
}
else {
temp->next = temp2;
temp = head2;
}
}
if (head1 != 0 && head2 != 0 && temp != 0) {
head1 = head1->next;
head2 = head2->next;
temp->next = 0;
}
}
while (result != 0)
{
l.AddToTail(result->num);
result = result->next;
}
return l;
}
如何在两个链表之间进行正确的切换?