为什么我的代码无法生成链表 [英] Why my code can not produce linked list

查看:75
本文介绍了为什么我的代码无法生成链表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了两个代码来生成链表。



一个代码使用insert函数来形成链表。

其他代码没有使用插入功能。



其中任何一个都没有编译器错误。



但是带有插入功能的代码在运行程序时给出BLANK SCREEN,因为其他代码运行良好



请帮我解决这个问题并解决我的问题。



我尝试过:



I wrote two codes to produce linked list.

One code uses insert function to form linked list.
Other code does not uses insert function for this.

There are no compiler errors in either of them.

BUT the code with insert function is giving BLANK SCREEN when I run the program where as the other code works well

Please help me figure this out and solve my problem.

What I have tried:

#include <iostream>

using namespace std;

struct node{
int data;
node*next;
};
node*head=NULL;
node* insert_(node*head,int size)
{

    for (int i=0;i<size;i++)>
    {
        node*temp=new node;
        temp->data=i;
        temp->next=head;
        head=temp;
        return head;
        }
}
int main()
{
insert_(head,4);
while(head)
{
    cout << head->data ;
    head=head->next;
}
}



没有插入功能的代码(效果很好)


CODE WITHOUT INSERT FUNCTION(which works well)

#include <iostream>

using namespace std;

struct node{
int data;
node*next;
};
node*head=NULL;

int main()
{
for (int i=0;i<5;i++)
    {
        node*temp=new node;
        temp->data=i;
        temp->next=head;
        head=temp;

        }



while(head)
{
    cout << head->data  ;
    head=head->next;
}
}

推荐答案

在插入版本中,您传递 head 作为参数使用与全局变量相同的名称。因为它是一个函数,所以使用局部(参数)变量,并保持全局变量的内容不变。



在第二个版本中使用全局变量为了获得类似的行为,将 insert 函数的返回值赋值给全局变量:<和


br />
In the insert version you are passing head as parameter using the same name as your global variable. Because it is a function, the local (parameter) variable is used and the content of the global variable is left unchanged.

In the second version the global variable is used and modified.

To get similar behaviour assign the return value of the insert function to your global variable:
head = insert_(head,4);







当然,解决方案1中报告的错误是我没有看到的,因为代码最初没有格式化。

[/ EDIT]




And of course the error reported in solution 1 which I did not saw because the code was initially not formatted.
[/EDIT]


我认为这是因为你已经回归了周期,但我想它应该没有了。

是这样的:

I think it is because you have return in for cycle, but i guess it should be out of it.
like this:
for (int i=0;i<size;i++)>
    {
        node*temp=new node;
        temp->data=i;
        temp->next=head;
        head=temp;
        
        }
return head;


这篇关于为什么我的代码无法生成链表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆