交错2个链接列表C ++
|
我在这里有解决方案代码:
// 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;
}
我确定这是错误的,但这是我现在唯一能想到的。请帮忙。谢谢
没有找到相关结果
已邀请:
2 个回复
诧不达
我看不到需要引用指针,因为front1中的第一个项目将继续保持第一个状态,并且您根本不需要弄混front2。
这会导致内存泄漏-您至少分配了sizeof(Node)个字节,但随后您丢失了对该指针的引用,因此您将无法再删除它。 另外,您对newNode不执行任何操作,因此也可能会将其丢弃。
基本上,您是在说front1会指向下一个元素,并且由于您传递了对front1的引用,因此您正在更改实际指针。最终,front1或front2将为NULL,并且循环将终止,因此,两个给定参数中的至少一个将变得无用。您再也不会改变,因此顺序将保持不变-您只是在浏览列表。 一种方法是将front2的值设置为front1-> next,然后交换指针并再次进行迭代:
我没有对此进行测试,但是应该可以正常工作了。如果您使用的是stl,则可以使用std :: swap()替换详细的交换代码。 这个想法很简单:假设您有两个列表: A-> B-> C-> NULL D-> E-> F-> NULL 您说A \的下一个项目将成为第二个列表中的第一个元素,因此D: A-> D-> E-> F-> NULL 然后第二个列表成为古代A \的后继者,因此只需B-> C-> NULL。然后,您前进以指向其新的下一个或D,这样您现在具有: D-> E-> F-> NULL B-> C-> NULL 然后重复: D-> B-> C-> NULL E-> F-> NULL B-> C-> NULL F->空 依此类推,直到满足NULL。然后仍然指向A的front1应该具有正确的顺序(也就是说,除非我非常错误:p)
乐遣杀屎
构造新节点。)