Listas Ligadas em C

list.h

/*
* list.h - definitions and declarations of the integer list
*/

#ifndef __LIST_H__

#define __LIST_H__

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

/* lst_iitem - each element of the list points to the next element */
typedef struct lst_iitem {
    int value;
    struct lst_iitem *next;
} lst_iitem_t;

/* list_t */
typedef struct {
    lst_iitem_t * first;
} list_t;

/* lst_new - allocates memory for list_t and initializes it */
list_t* lst_new();

/* lst_destroy - free memory of list_t and all its items */
void lst_destroy(list_t *);

/* lst_insert - insert a new item with value 'value' in list 'list' */
void lst_insert(list_t *list, int value);

/* lst_remove - remove first item of value 'value' from list 'list' */
void lst_remove(list_t *list, int value);

/* lst_print - print the content of list 'list' to standard output */
void lst_print(list_t *list);

#endif

 

list.c

/*
* list.c - implementation of the integer list functions
*/
#include <stdlib.h>
#include <stdio.h>
#include "list.h"

list_t* lst_new() {
    list_t *list;
    list = (list_t*) malloc(sizeof(list_t));
    list->first = NULL;
    return list;
}

void lst_destroy(list_t *list) {
    printf("lst_destroy\n");
    
    lst_iitem_t *head, *temp;
    head = list->first;
    
    while(head != NULL) {
        temp = head;
        head = head->next;
        free(temp);
    }
    free(list);
}

void lst_insert(list_t *list, int value) {
    printf("lst_insert: value=%d\n", value);
    
    lst_iitem_t *temp,*right;
    temp = (lst_iitem_t*)malloc(sizeof(lst_iitem_t));
    temp->value = value;
    temp->next = NULL;
    
    right=list->first;
    if(!right) {
        list->first = temp;
    } else {
        while(right->next != NULL) right = right->next;
        right->next = temp;
        right = temp;
        right->next = NULL;
    }
}

void lst_remove(list_t *list, int value) {
    printf("lst_remove: value=%d\n", value);
    
    lst_iitem_t *temp, *prev;
    temp = list->first;
    while(temp != NULL) {
        if(temp->value == value) {
            if(temp == list->first) {
                list->first = temp->next;
                free(temp);
                return;
            } else {
                prev->next = temp->next;
                free(temp);
                return;
            }
        } else {
            prev = temp;
            temp = temp->next;
        }
    }
}

void lst_print(list_t *list) {
    printf("lst_print\n");
    lst_iitem_t *temp = list->first;
    while(temp) {
        printf("%d, ", temp->value);
        temp = temp->next;
    }
    printf("\n");
}

 

Download

You may also like...

Deixar uma resposta

O seu endereço de email não será publicado. Campos obrigatórios marcados com *