单一链接列表遵循一种奇怪的显示模式

Singly linked list following a weird display pattern

本文关键字:一种 模式 显示 列表 链接 单一      更新时间:2023-10-16

如果我制作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;
        }
    }

}

请原谅,既然我已经尽了最大努力找到解决方案,那么事情就这么明显了。

我看到的问题:

  1. fnnpc未被初始化。

    将行更改为:

    struct node
    {
        char info;
        node* link;
    };
    node *f = NULL;
    node* nn = NULL;
    node* p = NULL;
    node* c = NULL;
    
  2. 更改线路

    if(f=='')
    

    if (f == NULL)
    

    这是一个风格的改变,但可读性更强。仅将''用于比较字符。使用NULL比较指针。

  3. 下面这句话似乎不对。

    nn=new node[sizeof(struct node)];
    

    它分配一个包含sizeof(struct node)项的对象数组,并返回指向该数组的指针。你只需要一个物体。将行更改为:

    nn=new node;
    

    有两条这样的线,if (f=='')下的每个块中都有一条。

  4. 您没有在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;
    
  5. 您正在修改display中的全局变量pc。如果在调用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个节点,第二个节点将添加到第一个节点所在的位置,而第一个节点将丢失。因此,您总是只看到添加的最后一个。