Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/151.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 无法在c+;的开头插入+;链表_C++_Linked List - Fatal编程技术网

C++ 无法在c+;的开头插入+;链表

C++ 无法在c+;的开头插入+;链表,c++,linked-list,C++,Linked List,我正在尝试创建一个函数,用于在链表的开头插入。我将我的代码与网络上的一些代码进行了比较,结果大致相同。但是,当我试图用代码块编译它时,输出的只是数字0。有人能解释一下为什么insertFirst函数不起作用,或者如果有错误就显示错误吗 struct node{ int data; struct node *next; }; node insertFirst(node *head, int newData){ node *temp = new node;

我正在尝试创建一个函数,用于在链表的开头插入。我将我的代码与网络上的一些代码进行了比较,结果大致相同。但是,当我试图用代码块编译它时,输出的只是数字0。有人能解释一下为什么insertFirst函数不起作用,或者如果有错误就显示错误吗

struct node{
    int data;
    struct node *next;
};

node insertFirst(node *head, int newData){
        node *temp = new node;
        temp -> data = newData;
        temp -> next = head;
        head = temp;

        return *head;
}

int main(){
 int i;

 node *first, *cur;

 first = new node;

 first -> data = 0;
 first -> next = 0;

 for(i = 1; i <= 10; i++){
    insertFirst(first, i);
 }

 cur = first;

 while(cur){
    cout << cur -> data << endl;
    cur = cur -> next;
 }
}
struct节点{
int数据;
结构节点*下一步;
};
节点insertFirst(节点*头,int newData){
node*temp=新节点;
临时->数据=新数据;
温度->下一步=头部;
压头=温度;
返回*头;
}
int main(){
int i;
节点*first,*cur;
第一个=新节点;
第一->数据=0;
第一个->下一个=0;
对于(i=1;iin
node insertFirst(node*head,int newData)
head是in参数,而不是in out

因此,在
main
中,它没有被更改


要更新
first
值,请使用
first=insertFirst(first,i);

您的第一个仍然是第一个,因为您在调用中不更新它。定义您的函数如下:

node insertFirst(node *&head, int newData)

因此,您将在“head”指针上获得一个引用,并将其传递回调用函数。

我认为SHR想要提到的是,您更改了代码,例如

node* insertFirst(node *head, int newData){
    node *temp = new node;
    temp -> data = newData;
    temp -> next = head;
    return temp;
}
以后你可以通过

for(i = 1; i <= 10; i++){
    first = insertFirst(first, i);
}

for(i=1;我有没有试过用调试器一步一步地检查代码,以找出它在哪里做了你不希望的事情?更新:我建议阅读。
insertFirst
中的
head
是本地副本,并且对它所做的任何分配(
head=temp;
)函数返回后将丢失。是否要通过引用传递?对于(i=1;我将原型更改为返回
node*
node insertLast(node*head,int newData){node*temp=new node;node*cur,*prev;temp->data=newData;temp->next=0;cur=head;prev=0;while(cur){prev=cur;cur=cur->next;}如果(!prev){head=temp;}否则{prev->next=temp;}返回*head;}
我也有上面的函数,并尝试在循环中以相同的方式实现它。它有什么不同?在您的方法中,您定义了参数
**node*head**
。因此,您可以将数据头点更改为调用方中的指针,而不是指针本身。对指针
**node*&head**
的引用我也将允许您访问指针。这与其他引用定义类似:
**node&x**
允许访问调用者变量,
**node x**
不允许。当您将节点的内容传递回时,您可以轻松地进行以下实验:在for循环中获取结果:
node other=insertFirst(first,i);
然后将其与for循环内另一行中的参数进行比较:
现在就可以回答您的问题:在insertLast函数中,
prev
从不为空,因此
head
从不更改。