Skip to content

Instantly share code, notes, and snippets.

@kibebr
Created October 31, 2019 23:13
Show Gist options
  • Save kibebr/7a3cc751dabdf4a81ed0663a1b8150b8 to your computer and use it in GitHub Desktop.
Save kibebr/7a3cc751dabdf4a81ed0663a1b8150b8 to your computer and use it in GitHub Desktop.
Simple Linked-List in C
#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