creat_list2功能有什么问题?

what is the problem in creat_list2 function?

本文关键字:什么 问题 功能 list2 creat      更新时间:2023-10-16

我想知道creat_list2函数有什么问题。 我在这段代码中遇到了问题,正如我知道的那样,它在creat_list2导致程序成功运行 当我停止此功能时,它要求用户输入将存储在列表 1 中的数字然后打印它们,但我看到的问题是在创建第二个列表的第二个功能中......,我明天必须提交我的作业,所以我希望是否有人可以帮助我解决这个问题。

#include<iostream>
using namespace std;
struct node{
int x;
node *next;
};
struct snode{
int y;
snode *next;
};
creat_list1(node *&head, node *&tail)
{
int num;
cout<<"enter numbern";
cin>>num;
while(num!=0)
{
node *np=new node;
np->x=num;
if(head==nullptr)
head=np;
else
tail->next=np;
tail=np;
tail->next=nullptr;
cout<<"enter number againn";
cin>>num;

}

}
creat_list2(node *&head, snode *shead, snode *stail)
{
int sum=0;
while(head!=nullptr)
{
for(int i=0;i<head->x;i++)
sum+=i;
snode *np= new snode;
np->y=sum;
if(head==0)
shead=np;
else
stail->next=np;
stail=np;
stail->next=nullptr;

}
head=head->next;

}
void print_list1 (node *head)
{
while(head!=nullptr)
{
cout<<head->x<<"t";
head=head->next;
}
}
void print_list2(snode *shead)
{
while(shead!=nullptr)
{
cout<<shead->y<<"t";
shead=shead->next;
}

}
main()
{
node *head=nullptr, *tail=nullptr;
snode *shead=nullptr, *stail=nullptr;
creat_list1(head,tail);
creat_list2(head,shead,stail);`enter code here`
print_list1(head);
print_list2(shead);

}

你的代码有几个问题,

  1. creat_list2(node *&head, snode *shead, snode *stail)(如果已更新(head喜欢head=head->next;它会反映在main.
  2. sheadstail只是一个本地指针,对像stail=np;这样的指针的任何更新都不会在"main
  3. 似乎有错别字if(head==0) shead=np;而是应该是if(shead==0) shead=np;导致空指针异常。

我试图在creat_list2修复错误,但功能对我来说仍然模棱两可,

void creat_list2(const node *head, node *&shead, node *&stail) //updated in argument
{
int sum = 0;
while (head != nullptr)
{
//for (int i = 0; i < head->x; i++)
//  sum += i;
node *np = new node;
np->x = sum;
if (shead == 0) //error : head instead shead
shead = np;
else
stail->next = np; 
stail = np;
stail->next = nullptr;
head = head->next;
}
}