Last active
April 27, 2018 07:37
-
-
Save decal/f76abbd4e06b77c60e5f06a1efc8fa2e to your computer and use it in GitHub Desktop.
🚋 Doubly linked list example using 4.4BSD queue.h preprocessor macros..
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* An implementation of doubly linked lists in ANSI C using sys/queue.h | |
* | |
* gcc -Wall -ansi -pedantic -O2 -o linked-lists linked-lists.c | |
* | |
* Written By: Derek Callaway [decal (AT) sdf {D0T} org] | |
* Last Modified: Fri Dec 29 09:22:40 UTC 2017 | |
* | |
*/ | |
#include<stdio.h> | |
#include<stdlib.h> | |
#include<sys/queue.h> | |
static void vexit(const char *funcname) { | |
perror(funcname); | |
exit(EXIT_FAILURE); | |
} | |
signed int main(int argc, char *argv[], char *envp[]) { | |
LIST_HEAD(listhead, entry) head; | |
struct entry { | |
int x; | |
LIST_ENTRY(entry) entries; /* List. */ | |
} *n1, *n2, *np; | |
LIST_INIT(&head); /* Initialize the list. */ | |
n1 = malloc(sizeof *n1); /* Insert at the head. */ | |
if(!n1) | |
vexit("malloc"); | |
n1->x = 1; | |
LIST_INSERT_HEAD(&head, n1, entries); | |
n2 = malloc(sizeof *n2); /* Insert after. */ | |
if(!n2) | |
vexit("malloc"); | |
n2->x = 2; | |
LIST_INSERT_AFTER(n1, n2, entries); | |
/* Forward traversal. */ | |
for (np = head.lh_first; np; np = np->entries.le_next) | |
printf("%d\n", np->x); | |
for(np = head.lh_first; np; np = np->entries.le_next) | |
LIST_REMOVE(np, entries); /* Delete. */ | |
exit(EXIT_SUCCESS); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment