多个链表可以共享相同的结构吗?

时间:2017-07-21 07:12:41

标签: c struct linked-list macros

我有不同的不同链表的结构,都有不同的数据类型变量。喜欢:

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

struct scorel {
    int no;
    struct scorel *rp;
};
struct namel{
    char a[10];
    struct scorel *rp;
    struct namel *dp;
};
void main(){
    int i,j,n,m;
    struct namel *temp,*head,*end,**s;
    struct scorel *tmp,*had,*nd;
    clrscr();
    printf("enter no of students");
    scanf("%d",&n);
    end=NULL;
    for(i=0;i<n;i++){
        temp=(struct namel*)malloc(sizeof(struct namel));
        printf("enter name\n");
        scanf("%s",temp->a);
        temp->rp=NULL;
        temp->dp=NULL;
        *(s+i)=temp;
        if(end==NULL){
            end=head=temp;
        }
        else {
            end->dp=temp;
            end=temp;
        }
        printf("enter no of scores");
        scanf("%d",&m);
        nd=NULL;
        for(j=0;j<m;j++){
            tmp=(struct scorel*)malloc(sizeof(struct scorel));
            printf("enter score\n");
            scanf("%d",&tmp->no);
            tmp->rp=NULL;
            if(nd==NULL){
                nd=had=tmp;
                temp->rp=tmp;
            }
            else {
                nd->rp=tmp;
                nd=tmp;
            }
        }
    }
    for(i=0;i<n;i++){
        temp=*(s+i);
        printf("%s-->",temp->a);
        tmp=temp->rp;
        while(tmp!=NULL){
            printf("%d-->",tmp->no);
            tmp=tmp->rp;
        }
        printf("\n");
    }
    getch();
}

任何可用于我可以使用相同的结构用于不同的不同链表。

我还看到了一系列链表,

struct node{
    int data;
    struct node *next;
}*head[5];

但仅此一点我们可以使用一种变量。 我希望每个链表都有不同类型的变量。

1 个答案:

答案 0 :(得分:0)

您可以通过两种方式进行链接列表。

第一种方法是将if(b1)字段与数据结构一起添加,然后您只能在一个列表中访问此结构

next

之后,当您将商品添加到关键列表时,您只需找到最后一项,然后设置struct myData { struct myData* next; int a; char b; float c; } last->next = current

另一种可能性是分离数据结构和列表输入

current->next = NULL;

现在,要将数据添加到链接列表,您可以执行以下操作:

//Linked list structure
struct nodeEntry {
    struct nodeEntry* next;
    void* data;
};

struct myData {
    int a;
    char b;
    float c;
};

在第二种情况下,链接列表中的每个项目都有自己的nodeEntry* ent = malloc(*ent); ent->data = pointerToMyData; ent->next = NULL; //Now find the last item in linked list and do: last->next = ent; 对象,这使您可以在多个链接列表中使用单个数据结构。

此方法称为多链表

Doubly Linked list vs Multi-linked list in C/C++

相关问题