A quick (singly) linked list demo in C
This file contains 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
#include <assert.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
typedef struct node { | |
char *str; | |
struct node *next; | |
} Node; | |
/* list */ | |
Node *list_make(int argc, char *argv[]) | |
{ | |
Node *curr, *head = NULL; | |
for (size_t i = argc - 1; i > 0; i--) { | |
curr = malloc(sizeof(Node)); | |
assert(curr != NULL); | |
curr->str = argv[i]; | |
curr->next = head; | |
printf("making node for arg #%lu at %p: str=%s, next=%p\n", | |
i, curr, curr->str, curr->next); | |
head = curr; | |
} | |
return head; | |
} | |
void list_print(Node *n) | |
{ | |
while (n != NULL) { | |
printf("printing node at %p: str=%s, next=%p\n", n, n->str, n->next); | |
n = n->next; | |
} | |
} | |
void list_free(Node *n) | |
{ | |
Node *tmp; | |
while (n != NULL) { | |
printf("freeing node at %p: str=%s, next=%p\n", n, n->str, n->next); | |
tmp = n; | |
n = n->next; | |
free(tmp); | |
} | |
} | |
/* main */ | |
/* | |
$ make ll | |
$ ./ll foo bar baz qux | |
making node for arg #4 at 0x7fe990404b20: str=qux, next=0x0 | |
making node for arg #3 at 0x7fe990404b30: str=baz, next=0x7fe990404b20 | |
making node for arg #2 at 0x7fe990404b40: str=bar, next=0x7fe990404b30 | |
making node for arg #1 at 0x7fe990404b50: str=foo, next=0x7fe990404b40 | |
--- | |
printing node at 0x7fe990404b50: str=foo, next=0x7fe990404b40 | |
printing node at 0x7fe990404b40: str=bar, next=0x7fe990404b30 | |
printing node at 0x7fe990404b30: str=baz, next=0x7fe990404b20 | |
printing node at 0x7fe990404b20: str=qux, next=0x0 | |
--- | |
freeing node at 0x7fe990404b50: str=foo, next=0x7fe990404b40 | |
freeing node at 0x7fe990404b40: str=bar, next=0x7fe990404b30 | |
freeing node at 0x7fe990404b30: str=baz, next=0x7fe990404b20 | |
freeing node at 0x7fe990404b20: str=qux, next=0x0 | |
*/ | |
int main(int argc, char *argv[]) | |
{ | |
if (argc < 2) { | |
printf("usage: %s <str1> <str2> ... <strN>\n", argv[0]); | |
return 1; | |
} | |
Node *head = list_make(argc, argv); | |
printf("---\n"); | |
list_print(head); | |
printf("---\n"); | |
list_free(head); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment