Created
February 13, 2020 23:47
-
-
Save acama/399c3762a4e68e2e30a182c04d0662e0 to your computer and use it in GitHub Desktop.
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> | |
typedef struct stuffox{ | |
int x; | |
struct stuffox* next; | |
}stuffox; | |
// instead of returning a new stuffox*, could've just changed the calling function's memory | |
// by defining as void Cons(int d, stuffox** list) | |
// that way is prob more efficient see LinkedList3.c | |
stuffox* Cons(int d, stuffox* list){ | |
stuffox* l = list; | |
stuffox* new =(stuffox*)malloc(sizeof(stuffox)); | |
new->x = d; | |
new->next = l; | |
return new; | |
free(top); | |
} | |
// Build a linked list with 3 stuffs | |
stuffox* BuildList(){ | |
// setup the pointers | |
stuffox *top = NULL; | |
stuffox *mid = NULL; | |
stuffox *last = NULL; | |
// allocate the memory (it is allocated in the heap) | |
top = (stuffox*)malloc(sizeof(stuffox)); | |
mid = (stuffox*)malloc(sizeof(stuffox)); | |
last = (stuffox*)malloc(sizeof(stuffox)); | |
// The nodes | |
top->x = 58; | |
top->next = mid; | |
mid->x = 27; | |
mid->next = last; | |
last->x = 36; | |
last->next = NULL; | |
return top; | |
free(top); | |
} | |
// Compute the length of the linked list | |
int Length(stuffox* s){ | |
int i = 0; | |
while(s != NULL){ | |
i++; | |
s = s->next; | |
} | |
return i; | |
} | |
int main(){ | |
stuffox* list = BuildList(); | |
int val; | |
int val2; | |
stuffox* newlist; | |
int length; | |
printf("Enter value to add to the list: "); | |
scanf("%d", &val); | |
newlist = Cons(val, list); | |
length = Length(newlist); | |
printf("The length of the new list is: %d\n", length); | |
printf("Enter value to add to the list: "); | |
scanf("%d", &val2); | |
newlist = Cons(val2,newlist); | |
length = Length(newlist); | |
printf("The length of the new list is: %d\n", length); | |
free(newlist); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment