在链接列表的开头添加节点。但我有虫子。这是我的代码
#include<iostream>
using namespace std ;
struct Node{
int x;
struct Node *next;
}
void add_begin(struct Node *a, struct Node *b){
if( b == NULL ){
b = a ;
}
else{
a -> next = b;
b = a;
}
}
void showList(struct Node *c){
while( c != NULL ){
cout << c->x << endl;
c = c -> next ;
}
}
int main(){
struct Node *List = NULL ;
struct Node *first = new ( struct Node ) ;
struct Node *second = new (struct Node) ;
first -> next = NULL;
second -> next= NULL ;
first -> x = 1;
second -> x = 2;
add_begin(first, List);
add_begin(second, List);
showList(List);
return 0 ;
}
此代码的输出为空。我认为该bug存在于 add_begin 函数中。但我不知道什么是错的。任何的想法 ?
答案 0 :(得分:4)
在函数add_begin
中,您正在更改局部变量b
,因为参数是通过值传递的,该函数处理参数的副本。因此局部变量的任何更改都不会影响参数。
按以下方式编写功能
void add_begin( Node * &head, int x )
{
Node *tmp = new Node { x, head };
head = tmp;
}
并将其称为
add_begin( List, 1 );
add_begin( List, 2 );
该功能将在列表中创建新节点。
如果您的编译器不支持使用new运算符的初始化列表,那么您可以重写像
这样的函数void add_begin( Node * &head, int x )
{
Node *tmp = new Node;
tmp->x = x;
tmp->next = head;
head = tmp;
}
考虑到您的代码中使用的语法
struct Node *first = new ( struct Node ) ;
无效。相反,你必须写
struct Node *first = new struct Node;
或只是
Node *first = new Node;
答案 1 :(得分:0)
您的add_begin
函数按值获取其参数。这意味着函数在其范围内接收指针的副本。当您在函数内部指定b = a
时,您将分配给副本,并且在该函数外部不会看到赋值。如果通过引用将指针传递给函数,则使用函数调用范围中的引用指针进行赋值。
试试这个:
void add_begin(struct Node * & a, struct Node * & b)
{
if( b == NULL )
{
b = a ;
}
else
{
a -> next = b;
b = a;
}
}
答案 2 :(得分:0)
void add_begin(struct Node *a, struct Node *b){
if( b == NULL ){
b = a ;
}
else{
a -> next = b;
b = a;
}
}
您只需更改指针b,而不是“列表”