Created
October 31, 2019 23:13
-
-
Save kibebr/7a3cc751dabdf4a81ed0663a1b8150b8 to your computer and use it in GitHub Desktop.
Simple 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> | |
int pushToEnd(int); | |
int pushToStart(int); | |
int setDefault(int*); | |
typedef struct node{ | |
int num; | |
struct node *next; | |
}node; | |
node *numList = NULL; | |
int main(void){ | |
pushToEnd(1); | |
pushToEnd(2); | |
pushToEnd(3); | |
pushToStart(10); | |
for(node *cursor = numList; cursor != NULL; cursor = (*cursor).next){ | |
printf("%i\n", (*cursor).num); | |
} | |
return 0; | |
} | |
int setDefault(int *toAdd){ | |
numList = malloc(sizeof(node)); | |
if(!numList) | |
return 1; | |
else{ | |
(*numList).num = *toAdd; | |
(*numList).next = NULL; | |
} | |
return 0; | |
} | |
int pushToEnd(int toAdd){ | |
node *cursor = numList; | |
if(cursor == NULL) | |
setDefault(&toAdd); | |
else{ | |
while((*cursor).next != NULL) | |
cursor = (*cursor).next; | |
cursor->next = malloc(sizeof(node)); | |
cursor->next->num = toAdd; | |
cursor->next->next = NULL; | |
} | |
return 0; | |
} | |
int pushToStart(int toAdd){ | |
node *cursor = numList; | |
if(cursor == NULL) | |
setDefault(&toAdd); | |
else{ | |
node *newNode = malloc(sizeof(node)); | |
if(!newNode) | |
return 1; | |
(*newNode).num = toAdd; | |
(*newNode).next = numList; | |
numList = newNode; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment