Last active
September 22, 2015 15:41
-
-
Save brenns10/171c62d1b91e4d49ce6f to your computer and use it in GitHub Desktop.
Linked List 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 <stdio.h> | |
#include <stdlib.h> | |
struct node { | |
int value; | |
struct node *next; | |
}; | |
void ll_print(struct node *list) | |
{ | |
while (list != NULL) { | |
printf("%d, ", list->value); | |
list = list->next; | |
} | |
printf("\n"); | |
} | |
struct node *ll_create(int arr[], int len) | |
{ | |
int i; | |
struct node *curr, *prev=NULL, *list; | |
for (i = 0; i < len; i++) { | |
curr = malloc(sizeof(struct node)); | |
curr->value = arr[i]; | |
if (prev == NULL) { | |
list = curr; | |
} else { | |
prev->next = curr; | |
} | |
prev = curr; | |
} | |
curr->next = NULL; | |
return list; | |
} | |
struct node *ll_reverse(struct node *list) | |
{ | |
struct node *curr = list, *prev = NULL, *temp; | |
while (curr != NULL) { | |
temp = curr->next; | |
curr->next = prev; | |
prev = curr; | |
curr = temp; | |
} | |
return prev; | |
} | |
void ll_free(struct node *list) | |
{ | |
struct node *next; | |
while (list != NULL) { | |
next = list->next; | |
free(list); | |
list = next; | |
} | |
} | |
int main(int argc, char *argv[]) | |
{ | |
int array[] = {1, 2, 3, 2, 5}; | |
struct node *list = ll_create(array, 5); | |
ll_print(list); | |
list = ll_reverse(list); | |
ll_print(list); | |
ll_free(list); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment