【发布时间】:2014-06-16 06:29:03
【问题描述】:
如果我创建 1 个节点并显示,则以下代码可以完美运行。但是,如果我插入 2 个或更多节点,则只显示最后输入的节点以及已经在链表中的节点。例如,如果我链接了 3 1 2 4 的列表,并且我连续输入 2 1 3 并调用显示函数,则输出 = 3 1 2 4 3。
struct node
{
char info;
node* link;
}*f,*nn,*p,*c;//variables to make new node, head and control previous and current
void create(char inf)
{
if(f=='\0')
{
nn=new node[sizeof(struct node)];
nn->info=inf;
nn->link='\0';
f=c=p=nn;
}
else
{
nn=new node[sizeof(struct node)];
nn->info=inf;
p->link=nn;
c=nn;
c->link='\0';
}
}
void display()
{
c=p=f;
while(c!='\0')
{
cout<<c->info<<" ";
p=c;
c=c->link;
}
cout<<endl;
}
int main()
{
while(3)
{
int sw=0;
cout<<"Enter \n1. to create list \n2. to display list"<<endl;
cin>>sw;
switch(sw)
{
case 1:{
char info;
cout<<"Enter info!"<<endl;
cin>>info;
create(info);
break;
}
case 2:display();
break;
default:
cout<<"Wrong entry, try again!"<<endl;
}
}
}
请原谅,因为我已尽力找到解决方案。
【问题讨论】:
-
给你的变量起一个有意义的名字,你就会知道你在哪里犯了错误。
f和c和p和nn不是你想要的。 -
c->link='\0'不是一个好主意。最好使用c->link = 0或c->link = NULL。 c->link 是一个指针,'\0'是 c++ 中的一个字符。
标签: c++ pointers linked-list nodes singly-linked-list