【问题标题】:Passing linked list that consists of three structures to a function将由三个结构组成的链表传递给函数
【发布时间】:2016-07-10 06:18:31
【问题描述】:

我知道如何创建具有两个结构的链表

为此,我声明了一个包含所有必要数据的结构。它看起来像这样:

struct Data{
    int numb;
    int date;
}

第二个结构表示具有head(即列表的第一个元素)和指向下一个节点的链接的节点。

struct llist{
    Data d;
    llist *next;
}

我想知道如果我想将我的 llist 添加到另一个代表 list 的结构中。

struct mainList{
    llist l;
}

我知道这可能会造成一些困难,因为我不太确定如何将 主列表 传递给函数。

这里,我尝试打印链表

void show(mainlist *ml){
    llist *u = ml->l;
    while(u){
        printf("Date: %s\t Name: %s\n",  u->d.dat, u->d.uname/* u->d.dat, u->d.uname*/);
        u=u->next;
    }
}

但出现错误提示“我无法在初始化时将 'llist' 'llist'' 所以,我在这里一无所知...有什么想法吗?

【问题讨论】:

  • 只有一个成员的struct 有什么意义?
  • 好吧,我用它来演示。主要目标是了解如何设置指针以便能够对链表进行操作。由于下面的答案,我现在对这个概念有了更好的理解)

标签: c list structure


【解决方案1】:

有很多问题 - 但是,与您所指的错误有关的是以下行:

llist *u = ml->l;  /* I guess you mean struct llist *u = ml->l */

show 函数中。这里ustruct llist *,但ml->lstruct llist,但不是指向它的指针。您需要将struct mainList 更改为:

struct mainList{
    struct llist *l;
}

所以ml->lstruct llist *

【讨论】:

    【解决方案2】:

    下面的工作解决方案,您的代码 sn-p 有一些问题。在 cmets 中指出...

    #include <iostream>
    using namespace std;
    
    struct Data {
        int numb;
        int date;
    };
    
    struct llist {
        Data d;
        llist *next;
    };
    
    struct mainList{
        llist *l; /*should be a pointer as you are referencing it as a pointer*/
    };
    
    void show(mainList *ml){ /*should be mainList, your code snippet shows 'mainlist'*/
        llist *u = ml->l;
        while(u){
            printf("Date: %d\t Name: %d\n",  u->d.date, u->d.numb/* u->d.dat, u->d.uname*/); /*your code snippet was using unavailable members of the struct*/
            u=u->next;
        }
    }
    
    int main ()
    {
    
        mainList ml;
    
        show(&ml);
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-17
      • 1970-01-01
      • 1970-01-01
      • 2015-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多