我一直在使用链接列表(出于学习目的,使用class
)。我这次决定使用friend
功能。该程序生成2个链接列表对象并调用friend void mergeAlternate(LL LL1, LL LL2);
函数。 (LL
是我班级的名字)
mergeAlternate
函数从链接列表中获取节点并交替放置它们。
例如:
LL1:1-> 2-> 3
LL2:4-> 5-> 6
Ans:1-> 4-> 2-> 5-> 3-> 6
这是我的代码::
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *next;
Node(int data) {
this->data = data;
this->next = NULL;
}
};
class LL {
private:
Node *head;
public:
LL() : head(NULL) {
createLL();
}
void printLL(Node *head) {
if(head == NULL)
head = this->head;
Node *temp = head;
while (temp != NULL) {
cout << temp->data << "-->";
temp = temp->next;
}
cout << "NULL" << endl;
}
void createLL() {
head = new Node(2);
head->next = new Node(7);
head->next->next = new Node(8);
head->next->next->next = new Node(1);
head->next->next->next->next = new Node(4);
head->next->next->next->next->next = new Node(9);
}
friend void mergeAlternate(LL LL1, LL LL2);
~LL() {
Node *temp = NULL;
while (head != NULL) {
temp = head;
head = head->next;
delete temp;
}
}
};
void mergeAlternate(LL LL1, LL LL2) {
Node *head1 = LL1.head, *head2 = LL2.head;
Node *temp1, *temp2;
while ((head1 != NULL) && (head2 != NULL)) {
temp1 = head1->next;
temp2 = head2->next;
head1->next = head2;
head2->next = temp1;
if (temp1 == NULL)
break;
head1 = temp1;
head2 = temp2;
}
if (head2 != NULL) {
head1->next = head2;
}
LL2.head = NULL;
LL1.printLL(LL1.head);
}
int main() {
LL newLL, newLL2;
newLL2.printLL(NULL);
mergeAlternate(newLL, newLL2);
newLL2.printLL(NULL);
}
我有一个printLL
函数用于打印链表。
问题在于我mergeAlternate
我按值传递2个链接列表。因此,我希望链接列表newLL
和newLL2
保持不变。但是,在main
中,在我打印链接列表时执行mergeAlternate
之后,我收到了运行时错误,并打印出类似的内容。
155672576-->155672672-->155672592-->155672688-->155672608-->155672704-->155672624-->155672720-->155672640-->155672736-->155672656-->NULL
虽然我希望再次打印相同的输入链接列表。为什么会这样?有什么我想念的吗?感谢您的帮助:))
ideone link :: http://ideone.com/apRCTw
答案 0 :(得分:4)
您的函数void mergeAlternate(LL LL1, LL LL2)
创建了两个新的局部变量LL
和LL2
,其成员head
也将指向newLL
和{{}的相同内存地址1}}分别指向。因为newLL2
和LL1
是函数的局部变量,所以当函数结束时,将调用它们各自的析构函数。根据你的析构函数定义:
LL2
它将取消分配~LL() {
Node *temp = NULL;
while (head != NULL) {
temp = head;
head = head->next;
delete temp;
}
}
Nodes
和LL1
的{{1}},但因为它们与LL2
和newLL
的内存地址相同,这意味着当函数结束时,最后两个对象将在其成员newLL2
和后续引用中具有垃圾值,这将在尝试访问其值时导致错误。
答案 1 :(得分:3)
我看到那里有一些陷阱。
您按值传递列表,包括其内部指针。这意味着在函数内通过复制创建的列表指向与原始列表相同的数据结构。因此,您在函数内所做的任何更改都将被&#34;看到&#34;在原始列表中。
你做了所谓的&#34;浅拷贝&#34;的清单。你没有复制列表的内容。
要解决此问题,您需要制作列表的深层副本。创建一个创建列表副本的函数,或者在迭代它们时创建节点的副本。第一种解决方案可能不太容易出错。
答案 2 :(得分:2)
您按值传递LL
,但由于该类只是指向节点的指针的包装器,因此您实际上将两个指针传递到相应列表的头部。因为您正在修改节点这些指针指向,与调用者的LL
实例使用的节点相同,您正在有效地修改调用者列表。只需考虑调用函数后应该有多少个不同的节点:
LL1: 1->2->3
LL2: 4->5->6
Ans: 1->4->2->5->3->6
这是LL1和LL2的2个3节点加上答案的6个节点,共计12个节点。构建LL1和LL2时,您分配了6个节点。
要解决此问题,您需要在合并列表时制作(分配)节点副本,仅修改这些副本。