User Tools

Site Tools


One-way chain sample

chain.c
/*
 * Copyright 2020 Oleg Borodin  <borodin@unix7.org>
 */
 
#include <stdio.h>
#include <stdlib.h>
 
struct cell {
    int data;
    struct cell* next;
};
 
typedef struct cell cell_t;
 
cell_t* new_chain(int data) {
    cell_t* cell = malloc(sizeof(cell_t));
    cell->next = NULL;
    cell->data = data;
    return cell;
}
 
cell_t* chain_add(cell_t* root, int data) {
    cell_t* next = malloc(sizeof(cell_t));
    next->data = data;
    next->next = NULL;
    cell_t* curr = root;
    for (;;) {
        if (curr->next == NULL) {
            curr->next = next;
            break;
        }
        curr = curr->next;
    }
    return next;
}
 
typedef void (*chain_iter_t)(int pos, cell_t* cell);
 
void chain_iter(cell_t* root, chain_iter_t iter) {
    cell_t* curr = root;
    int pos = 0;
    for (;;) {
        if (curr == NULL) {
            break;
        }
        iter(pos, curr);
        curr = curr->next;
        pos++;
    }
}
 
int chain_len(cell_t* root) {
    cell_t* curr = root;
    int len = 0;
    for (;;) {
        if (curr == NULL) {
            break;
        }
        curr = curr->next;
        len++;
    }
    return len;
}
 
 
void cell_free(cell_t* cell) {
    if (cell == NULL) return;
    if (cell->next != NULL) free(cell->next);
    free(cell);
}
 
void chain_del(cell_t* root, int num) {
    cell_t* curr = root;
    int pos = 1;
    for (;;) {
        if (curr == NULL) {
            break;
        }
        if (pos == num) {
            cell_t* fwd = NULL;
            if (curr->next != NULL) {
                fwd = curr->next->next;
            }
            cell_free(curr->next);
            curr->next = fwd;
            break;
        }
        pos++;
        curr = curr->next;
    }
    return;
}
 
 
void iter(int pos, cell_t* cell) {
    printf("%d: %d\n", pos, cell->data);
}
 
int main(int argc, char **argv) {
 
    cell_t* root = new_chain(0);
    chain_add(root, 1);
    chain_add(root, 2);
    chain_add(root, 3);
    chain_add(root, 4);
 
    chain_iter(root, iter);
 
    printf("len = %d\n", chain_len(root));
 
    chain_del(root, 4);
    chain_del(root, 1);
    chain_iter(root, iter);
    printf("len = %d\n", chain_len(root));
 
    return 0;
}
$ "./chain"
0: 0
1: 1
2: 2
3: 3
4: 4
len = 5

0: 0
1: 2
2: 3
len = 3