C++ 在C+中复制链表时使用指针与运算符地址+;
我做了下面的链表结构和printList函数。两者都正常工作:C++ 在C+中复制链表时使用指针与运算符地址+;,c++,pointers,linked-list,singly-linked-list,C++,Pointers,Linked List,Singly Linked List,我做了下面的链表结构和printList函数。两者都正常工作: struct Node{ int data; Node *np; }; void printList(Node *x){ cout << x->data << " "; if (x->np != NULL){ printList(x->np); } return; } 这不起作用: Node * copyList(Node
struct Node{
int data;
Node *np;
};
void printList(Node *x){
cout << x->data << " ";
if (x->np != NULL){
printList(x->np);
}
return;
}
这不起作用:
Node * copyList(Node *x){
Node y = {x->data,NULL};
if (x->np != NULL){
y.np = copyList(x->np);
}
return &y;
}
我有点不明白为什么。我假设指针实质上引用了内存地址,返回&y也可以…在第二种情况下,当函数调用结束时,您正在创建的节点y对象将超出范围。您返回的地址将无效。一旦
copyrist
退出,其所有局部变量都将被销毁;返回的指针指向的位置不再存在节点
对象。下次调用函数时,该内存可能会被用于其他用途。第一个函数也是无效的,因为通常x
的参数可以等于NULL。所以在语句中有未定义的行为
y->data = x->data;
正确的函数可以如下所示
Node * copyList( const Node *x )
{
if ( x == NULL )
{
return NULL;
}
else
{
Node *y = new Node { x->data, copyList( x->np ) };
return y;
}
}
甚至像
Node * copyList( const Node *x )
{
return ( x == NULL ) ? NULL : new Node { x->data, copyList( x->np ) };
}
函数printList
也存在同样的问题。应该这样定义
void printList( const Node *x )
{
if ( x == NULL )
{
std::cout << std::endl;
}
else
{
std::cout << x->data << ' ';
display( x->np );
}
}
void打印列表(常量节点*x)
{
如果(x==NULL)
{
std::cout取决于您的编译器,如果您打开警告,它应该能够准确地告诉您为什么这不起作用。
void printList( const Node *x )
{
if ( x == NULL )
{
std::cout << std::endl;
}
else
{
std::cout << x->data << ' ';
display( x->np );
}
}