求助:单链表合并指针问题
首先做一个试验
#include<iostream>
using namespace std;
template<class T>
struct LinkNode {
T data;
LinkNode<T>* link;
LinkNode(LinkNode<T>* ptr = NULL) { link = ptr; }
LinkNode(const T& item, LinkNode<T>* ptr = NULL) {
data = item;
link = ptr;
}
};
int main() {
LinkNode<int>* p1 = new LinkNode<int>;
LinkNode<int>* p2 = new LinkNode<int>;
LinkNode<int>* tmp = new LinkNode<int>;
tmp->data = 3;
p1->link = tmp;
p2->link = tmp;
cout << "p1->link->data:" << p1->link->data << endl;
cout << "&p1->link: " << &p1->link << endl;
cout << "p2->link->data:" << p2->link->data << endl;
cout << "&p2->link: " << &p2->link << endl;
p2->link->data = 2;
cout << "p1->link->data:" << p1->link->data << endl;
cout << "&p1->link: " << &p1->link << endl;
cout << "p2->link->data:" << p2->link->data << endl;
cout << "&p2->link: " << &p2->link << endl;
return 0;
}
运行结果如下
说明两个节点的link可以指向同一个节点,修改一个节点的link会对另一个节点有影响,但编译器没有报错
在单链表合并的函数里
template<typename T>
void merge(List<T>& a, List<T>& b) {
LinkNode<int>* prea = a.getHead();
LinkNode<int>* ptra = prea->link;
LinkNode<int>* preb = b.getHead();
LinkNode<int>* ptrb = preb->link;
while (ptra != NULL && ptrb != NULL) {
if (ptra->data > ptrb->data) {
LinkNode<int>* tmp = ptrb->link;
ptrb->link = ptra;
prea->link = ptrb;
preb->link = tmp;
ptrb = tmp;
}
prea = prea->link;
ptra = prea->link;
}
if (ptrb != NULL) {
prea->link = ptrb;
cout << prea->link << endl;
cout << preb->link << endl;
preb->link = NULL;
cout << preb->link << endl;
}
}
最后的if
写成这样时
if (ptrb != NULL) {
prea->link = ptrb;
cout << prea->link << endl;
cout << preb->link << endl;
preb->link = NULL;
cout << preb->link << endl;
}
运行结果如下
并且编译器没有报错
但如果去掉preb->link = NULL
if (ptrb != NULL) {
prea->link = ptrb;
cout << prea->link << endl;
cout << preb->link << endl;
//preb->link = NULL;
cout << preb->link << endl;
}
在有如下运行结果的同时
编译器还会报错
最开始的试验说明两个节点的指针可以指向同一个节点,但是为什么会出错呢