0

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;
}
0

Fun! This program does not compile on IDE v98 with make {name}. insert function (non-void) has no return.

Speaking of the insert function: If head is the head of the list, should anything point to it? (as is done here: new->next = head;

Looking for bugs in all the wrong places :). Concentrate on insert. Use debug50.

1
  • Thank you! I'll look into that. I wasn't using the CS50 IDE but a Ubuntu desktop environment, since it wasn't directly related to the problem set and I'm trying to learn Linux anyway. Thanks again. Apr 2 '17 at 15:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .