Skip to content

Instantly share code, notes, and snippets.

@lnznt
Created May 1, 2012 01:53
Show Gist options
  • Save lnznt/2564344 to your computer and use it in GitHub Desktop.
Save lnznt/2564344 to your computer and use it in GitHub Desktop.
[sample] linked list (C language)
/*
llist.h
*/
#ifndef INCLUDED_LLIST_H
#define INCLUDED_LLIST_H
#define llist_init(l_) ((l_)->next = (l_)->prev = (l_))
#define llist_next(l_) ((l_)->next)
#define llist_prev(l_) ((l_)->prev)
#define llist_ins_next(l_, x_) (\
(x_)->next = (l_)->next ,\
(x_)->prev = (l_) ,\
(l_)->next->prev = (x_) ,\
(l_)->next = (x_) )
#define llist_ins_prev(l_, x_) (\
(x_)->prev = (l_)->prev ,\
(x_)->next = (l_) ,\
(l_)->prev->next = (x_) ,\
(l_)->prev = (x_) )
#define llist_del(l_) (\
(l_)->prev->next = (l_)->next ,\
(l_)->next->prev = (l_)->prev )
#endif /* !INCLUDED_LLIST_H */
/*
sample-llist.c
to build:
$ make sample-list
*/
#include <stdio.h> /* printf() */
#include <stdlib.h> /* EXIT_SUCCESS */
#include "llist.h"
typedef struct station_t {
char *name;
struct station_t *next; /* 'next' must be defined */
struct station_t *prev; /* 'prev' must be defined */
} STATION_t;
int main(void)
{
STATION_t head; /* head of list */
STATION_t tokyo = {"Tokyo" }, *s1 = &tokyo,
nagoya = {"Nagoya" }, *s2 = &nagoya,
shin_ohsaka = {"Shin-Ohsaka"}, *s3 = &shin_ohsaka;
STATION_t *st;
llist_init(&head); /* (head) */
llist_ins_next(&head, s1); /* (head) - [Tokyo] */
llist_ins_next(s1, s2); /* (head) - [Tokyo] - [Nagoya] */
llist_ins_next(s2, s3); /* (head) - [Tokyo] - [Nagoya] - [Shin-Ohsaka] */
for (st = llist_next(&head); st != &head; st = llist_next(st)) {
printf("-> %s ", st->name);
}
printf("\n");
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment