I am a newbie to C and programming and I have attempted to come up with my own functions for a singly linked list – including create, insert, search and delete. I would really appreciate it if a kind soul could take a look at my code and spot any mistakes and point out how I could improve it π My code is as follows:
#include <cs50.h> #include <stdio.h> #include <stdlib.h> //Definition of a node structure and its fields typedef struct sllist { int val; struct sllist *next; } sllnode; //Creation of a linked list sllnode* create(int val) { //Creation of a node using dynamic memory allocation sllnode* ptr = malloc(sizeof(sllnode)); sllnode* head = NULL; sllnode* list = NULL; //Checking for NULL if(NULL == ptr) { return NULL; } //Inserting val into the upper field of the node ptr->val = val; //Setting lower field of node to NULL ptr->next = NULL; list = head = ptr; return ptr; } //Insertion of node into list sllnode* insert(sllnode* head, int val) { //Checking for NULL if(NULL == head) { return NULL; } //Creation of a node using dynamic memory allocation sllnode* ptr = malloc(sizeof(sllnode)); //Inserting val into the upper field of the node ptr->val = val; //Setting lower field of node to NULL ptr->next = NULL; //Chaining two nodes together ptr->next = head; //Shifting head and list pointer to front of list list = head = ptr; return ptr; } //Searching a linked list bool search(int val, sllnode *list) { //Declaration of pointer list (to identify start of list) sllnode* ptr = list; //Execute loop until pointer points to NULL (very end of list) while(ptr != NULL) { //If integer being searched for is stored inside upper field of that node of the list if(ptr->val == val) { return true; } //Else pointer should point to next field of next node (traverse) ptr = ptr->next; } return false; } //Deleting an entire linked list void destroy(sllnode* list) { //Declaration of pointer list (to identify start of list) sllnode* ptr = list; //Checking for NULL if(NULL == list) { return NULL; } while(ptr->next != NULL) { //list pointer should point to upper field of every node in the linked list list = ptr->val; } if(ptr->next == NULL) { //list pointer is now pointing to last node of linked list list = ptr->val; } //Deleting all nodes in linked list from right to left while(list = ptr->val) { free(ptr); } }
I also have two questions to ask regarding the following line of code:
//Setting lower field of node to NULL ptr->next = NULL;
I understand that the intention behind the above line of code is to make the next pointer in the node point to NULL. So does that mean that ptr will store the memory address of the next field of the node? Does that also mean that the next field of that node will store memory address of 0?