Created
November 18, 2020 18:38
-
-
Save cbscribe/4e7d272eacd5d6b1a93cade2eeed28b7 to your computer and use it in GitHub Desktop.
In-class example using linked lists
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
| #include <stdio.h> | |
| #include <stdlib.h> | |
| typedef struct node | |
| { | |
| int value; | |
| struct node *next; | |
| } node; | |
| node *list = NULL; | |
| void append(int i) | |
| { | |
| node *n = malloc(sizeof(node)); | |
| n->value = i; | |
| n->next = NULL; | |
| if (list == NULL) | |
| { | |
| list = n; | |
| } | |
| else | |
| { | |
| node *ptr = list; | |
| while (ptr->next != NULL) | |
| { | |
| ptr = ptr->next; | |
| } | |
| ptr->next = n; | |
| } | |
| } | |
| int main(void) | |
| { | |
| for (int i = 0; i < 5; i++) | |
| { | |
| // allocate a new node | |
| node *n = malloc(sizeof(node)); | |
| if (n == NULL) | |
| { | |
| return 1; | |
| } | |
| n->value = i; | |
| n->next = list; | |
| list = n; | |
| } | |
| append(10); | |
| // print list | |
| for (node *ptr = list; ptr != NULL; ptr = ptr->next) | |
| { | |
| printf("%i ", ptr->value); | |
| } | |
| printf("\n"); | |
| // free all nodes | |
| node *ptr = list; | |
| while (ptr != NULL) | |
| { | |
| node *tmp = ptr; | |
| ptr = ptr->next; | |
| free(tmp); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment