Main for function on linked lists

1

I'm having trouble creating a main so I can test if my function is working well. My program is as follows: LInt fromArray (int v [], int N) which, given an array v with N elements, sorted in ascending order, builds an ordered list with array elements, in the same order. Here's what I was able to do:

typedef struct slist 
{
  int valor;
  struct slist *prox;
} *LInt;

LInt fromArray (int v[], int N)
{
  LInt nova = (LInt)malloc(sizeof (struct slist));
  LInt aponta = nova;
  int i;

  if (N==0) 
  { return NULL; }

  for (i = 0 ; i < N ; i++)
  {
    nova->valor = v[i];
    nova->prox = (LInt)malloc(sizeof (struct slist));
    nova = nova->prox;
  }

   nova = NULL;

   return aponta;
}

How do I main for this function? And in general for functions on linked lists, what is the main aspect to take into account when creating main?

    
asked by anonymous 15.05.2015 / 00:15

1 answer

2

To add an element at the end of a linked list you must go through the entire list. To add an element at the beginning of a linked list you do not need anything special.

To convert an array already sorted into a list, I suggest you start adding the end of the array to the beginning.

I wrote a complete example (you can also see running on ideone ) - as you see, nothing special is needed in the% with%. In my function main() you need to flag the empty initial list with NULL ( list_fromarray() ) and use the pointer address when calling functions that change the list.

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

struct list {
    int value;
    struct list *next;
};

void list_add(struct list **li, int value);
struct list *list_fromarray(int *v, int n);
void list_print(struct list *li, const char *msg);
void list_free(struct list *li);

int main(void) {
    struct list *list;
    int test[] = {1, 4, 8, 9, 13, 42};
    list = list_fromarray(test, sizeof test/sizeof *test);
    list_print(list, "final list");
    list_free(list);
}

struct list *list_fromarray(int *v, int n) {
    struct list *li = NULL;
    for (int k = n - 1; k >= 0; k--) {
        list_add(&li, v[k]);
    }
    return li;
}

void list_add(struct list **li, int value) {
    struct list *node;
    node = malloc(sizeof *node);
    node->value = value;
    node->next = *li;
    *li = node;
}

void list_print(struct list *li, const char *msg) {
    printf("%s:", msg);
    while (li) {
        printf(" %d", li->value);
        li = li->next;
    }
    puts("");
}

void list_free(struct list *li) {
    while (li) {
        struct list *bak = li;
        li = li->next;
        free(bak);
    }
}
    
15.05.2015 / 12:22