单一链接列表遵循一种奇怪的显示模式
Singly linked list following a weird display pattern
如果我制作1个节点并显示,下面的代码可以完美地工作。但是,如果插入2个或多个节点,则只显示最后输入的节点和已在链表中的节点。例如,如果我链接了3 1 2 4的列表,并且我连续输入2 1 3并调用显示函数,则输出=3 1 2 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==' ')
{
nn=new node[sizeof(struct node)];
nn->info=inf;
nn->link=' ';
f=c=p=nn;
}
else
{
nn=new node[sizeof(struct node)];
nn->info=inf;
p->link=nn;
c=nn;
c->link=' ';
}
}
void display()
{
c=p=f;
while(c!=' ')
{
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
、nn
、p
和c
未被初始化。将行更改为:
struct node { char info; node* link; }; node *f = NULL; node* nn = NULL; node* p = NULL; node* c = NULL;
-
更改线路
if(f==' ')
至
if (f == NULL)
这是一个风格的改变,但可读性更强。仅将
' '
用于比较字符。使用NULL
比较指针。 -
下面这句话似乎不对。
nn=new node[sizeof(struct node)];
它分配一个包含
sizeof(struct node)
项的对象数组,并返回指向该数组的指针。你只需要一个物体。将行更改为:nn=new node;
有两条这样的线,
if (f==' ')
下的每个块中都有一条。 -
您没有在
else
块下正确创建链接。nn=new node[sizeof(struct node)]; nn->info=inf; p->link=nn; // This is good only for the second item. // When you add the third item, the second item becomes an orphan. // When you add the fourth item, the third item becomes an orphan. c=nn; c->link=' ';
您需要的是:
nn=new node; nn->info=inf; nn->link = NULL; c->next = nn; c = nn;
-
您正在修改
display
中的全局变量p
和c
。如果在调用display
之后尝试添加更多项目,则会出现意外行为。在display
中使用局部变量可以防止出现该问题。void display() { Node* n = f; while( n != NULL) { cout << n->info << " "; n = n->link; } cout << endl; }
建议清理
全局范围中不需要变量nn
。仅在create
中使用。将其从全局范围中删除,并将其放入create
中。
您根本不需要全局变量p
。您认为它唯一有用的地方是else
块。但是,正如你所看到的,那里并不需要它。
使用NULL
而不是' '
来比较指针。
问题出在这一行:
p->link=nn;
您正在同一位置添加新节点,但未更新"p"。因此,如果添加2个节点,第二个节点将添加到第一个节点所在的位置,而第一个节点将丢失。因此,您总是只看到添加的最后一个。
相关文章:
- 只需要知道我在c ++中打印模式的方式是否有效,或者有另一种方法可以有效地做到这一点
- 是否有一种设计模式或面向对象的基本原则来处理这种共享资源的情况?
- 在我的情况下,多重继承是一种好的设计模式吗?
- 类型擦除和一种模板方法模式
- 一种在 Mac 上强制关闭模式 QFileDialog 的方法
- 一种奇怪的构造模式
- 是否有一种模式可以使用协议缓冲区而不针对LibProtobuf链接
- C 双重调度,出厂模式或一种从接收到的序列数据创建派生对象的方法
- 寻找一种设计模式以应用于C++
- 是否有一种模式来描述哪个对象控制另一个对象的生命周期?
- 这种Pro*C模式是一种最佳实践,还是有文档记录
- 有没有一种方法可以在c++中实现动态工厂模式
- 仍然是一种观察者模式
- GetLastError()是一种设计模式吗?这是好的机制吗
- 释放模式是一种特殊模式吗
- 这种c++单例模式和方法公开是一种好的实践吗?
- XML类描述到c++类描述:一种设计模式
- 在Windows OpenGL应用程序中是否有一种优雅的方式来处理在全屏和窗口模式之间切换
- "delete p; p = NULL(nullptr);"是一种反模式吗?
- 寻找一种模式来避免在实现虚函数时使用dynamic_cast