Arun Srikanth Sridhar Arun Srikanth Sridhar - 3 months ago 22
C Question

Linked lists with structures

I am trying to implement an array of linked lists. Now the linked lists contains a struct not a single data. I am not sure how to proceed with this. When I do the following I get a lot of errors.

How should I go about this ?
Thanks

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

void main(){

int i,j;

typedef struct{
int a;
int b;
}Integers;

typedef struct{
Integers Int;
struct Node *next;
}Node;

Node *curr,*head,*nullhead;
curr=(Node *)malloc(sizeof(Node)*100);
//head=(Node *)malloc(sizeof(Node)*100);


for (i=0;i<10;i++){
head[i]= NULL;
for(j=0;j<10;j++){
curr[i].Int.a=j;
curr[i].Int.a=j;
curr[i].next=head[i];
head[i]=curr[i];
}
}

}

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

typedef struct _node {
  int data;
  struct _node *next;
} Node;

Node *addfrontnode(Node **head,int data){
  Node *curr;

  curr = (Node *)malloc(sizeof(Node));
  curr->data = data;
  curr->next = *head;
  return curr;
}

int main(void) {
  int i, j;

  Node **head, *curr;
  head = (Node **)malloc(sizeof(Node *));

  for(j=1; j<=10; j++)
  {
    head[j] = NULL;
    curr = NULL;
    for(i=1; i <= 10; i++) {
      curr = addfrontnode(&head[j],i);
      head[j] = curr;
    }
  }

  i = 10;

  while(head[i]) {
    printf("%d\n",head[i]->data);
    head[i] = head[i]->next;
  }

  return 0;
}
Comments