this is not directly related to the problem set, but maybe somebody can help me out nevertheless. I'm trying to understand the singly-linked list and so I've attempted to write one on my own, based on the CS50 video. However, I'm kind of stuck. I can create the list and add new elements but my find
and printList
functions don't work (don't find/print anything). Can anybody point me in the right direction? Thanks so much in advance.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct sllist {
int val;
struct sllist* next;
} sllnode;
// create a linked list
sllnode* create (int n) {
sllnode* first = malloc(sizeof(sllnode));
if (first == NULL) {
printf("Couldn't create a list.\n");
exit(1);
}
first->val = n;
first->next = NULL;
return first;
}
// find an element
bool find (sllnode* head, int n) {
sllnode* crawler = head;
while (crawler != NULL) {
if (crawler->val == n) {
printf ("Found %d\n", n);
return true;
}
else
crawler = crawler->next;
}
printf("Couldn't find %d\n", n);
return false;
}
// insert a new node
sllnode* insert (sllnode* head, int n) {
sllnode* new = malloc(sizeof(sllnode));
if (new == NULL) {
printf("Couldn't allocate new memory.\n");
exit(1);
}
new->val = n;
new->next = NULL;
new->next = head;
head = new;
}
void printList (sllnode* head) {
sllnode* crawler = head;
while (crawler != NULL) {
printf("%d\n", crawler->val);
crawler = crawler->next;
}
}
int main (void) {
// create new list
sllnode* head = create(0);
// insert some new nodes
sllnode* n1 = insert(head, 100);
sllnode* n2 = insert(head, 200);
sllnode* n3 = insert(head, 300);
// find some node
find(head, 300);
printList(head);
printf("%d\n", n1->val);
printf("%d\n", n2->val);
printf("%d\n", n3->val);
free(head);
return 0;
}