交错2个链表C++

interleave 2 linked list C++

本文关键字:C++ 链表 2个 交错      更新时间:2023-10-16

我在这里有解决方案代码:

// Pre-condition: The fronts of two linked lists are provided.
// Post-condition: A linked list is returned that is the result of
// interleaving the elements from each provided list. 
// (e.g. {1, 2, 3} & { 4, 5, 6} would return {1, 4, 2, 5, 3, 6}
Node* interleave( Node*& front1, Node*& front2 ) {
    if( !front1 ) return front2;
    if( !front2 ) return front1;
    Node* third = front1->next; //this will become the third element
    Node* fourth = front2->next; // this will be come the fourth element
    front1->next = front2;
    front2->next = third;
    third = interleave(third, fourth);
    return front1;  
}

我有点理解它,但我永远无法想出这样的东西,因为我非常不擅长递归。有没有其他方法可以非递归地解决这个问题?如果是的话,你能给我一个提示吗?我试过这个:

Node* interleave( Node*& front1, Node*& front2 ) {
    Node* newNode = new Node;
    while(front1!=NULL && front2!=NULL){
        newNode = front1->next;
        newNode = front2->next;
        front1 = front1->next;
        front2 = front2->next;
     }
    return newNode;
}

我确信这是错误的,但这是我现在唯一能想到的。请帮忙。感谢

试着在一张纸上平行绘制两个链表。在节点中放一些数字,只是为了区分它们。考虑一下如何将它们重新连接起来,形成一个单独的列表,从开头(或"前面")开始,然后往下看。请注意,您必须跟踪一些特殊节点,如结果列表的第一个节点和其他几个节点。模式应该变得清晰起来。

(请注意,不需要使用new构建新节点。)

您的代码中有几个错误:

Node* interleave( Node*& front1, Node*& front2 )

我认为没有必要引用指针,因为front1中的第一个项目将继续是第一个,而且您根本不需要处理front2。

Node* newNode = new Node;
while(front1!=NULL && front2!=NULL){
    newNode = front1->next;

这导致了内存泄漏——您至少分配了sizeof(Node)字节,但随后丢失了对指针的引用,因此无法再删除它。此外,您没有对newNode执行任何操作,因此可能也会将其丢弃。

front1 = front1->next;
front2 = front2->next;

基本上,您告诉front1将指向下一个元素,并且由于您传递了对front1的引用,因此您正在更改实际指针。最终,front1或front2将为NULL,循环将终止,因此两个给定参数中至少有一个将变得无用。接下来你永远不会改变,所以顺序将保持不变——你只是在浏览列表。

一种方法可以是将front2的值设置为front1->next,然后交换指针并再次迭代:

Node *a = front1, *b = front2;
while (a && b) {
    Node* tmp = a->next;
    a->next = b;
    b = tmp;
    a = a->next;
}
return front1;

我没有测试这个,但它应该接近工作。如果使用stl,可以用std::swap()替换详细的交换代码。这个想法很简单:假设你有两个列表:

A->B->C->NULL
D->E->F->空

你说A的下一个项目将是第二个列表中的第一个元素,所以D:

A->D->E->F->空

然后第二个列表成为古代A的继承者,所以只有B->C->NULL。然后你前进一步,指向新的下一步,或者D,所以你现在有了:

D->E->F->NULL
B->C->空

然后你重复:

D->B->C->空
E->F->空

B->C->NULL
F->空

依此类推,直到满足NULL为止。那么仍然指向A的front1应该有正确的序列(也就是说,除非我大错特错:p)