Main for function on linked lists

Asked

Viewed 134 times

1

I’m having a hard time creating a main to test if my function is going well. My program is as follows: : Lint fromArray (int v[], int N) which, given an array v with N elements, ordered in ascending order, constructs an ordered list of the array elements in the same order. Here’s what I could 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 the main?

1 answer

2

To add an item at the end of a linked list you need to scroll through the entire list.
Adding an element at the beginning of a linked list does not require anything special.

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

I wrote a complete example (which you can also see running in the ideone) -- as you can see there’s nothing special about the function main(). In my job list_fromarray() you need to flag the empty initial list with NULL (struct list *li = NULL;) 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);
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.