如何解决交错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,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;
}
我确定这是错误的,但这是我现在唯一能想到的。请帮忙。谢谢
解决方法
您的代码中有一些错误:
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-> 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)
,尝试在一张纸上并行绘制两个链接列表。在节点中放入一些数字,以区别它们。考虑如何重新连接它们以形成一个列表,从头(或\“ front \”)开始,然后向下进行。请注意,您必须跟踪一些特殊节点,例如结果列表的第一个节点以及其他几个节点。模式应该变得清晰。
(请注意,无需使用new
构造新节点。)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。