DEV Community

loading...

Discussion on: Finally, a post on singly linked list I understand

Collapse
wiz profile image
wiz

Great work! I have few tips that I want to share:
You can also declare head as a pointer to the structure node.
And then you can start creating nodes in the linked list. Since a head is just a pointer to the first node so this way you can achieve that by not making it a node in actual with data and next part.
Actually, this approach is common in C.

struct ListNode *head = NULL;

Then inside your insert function, since you are adding in front only

    newnode = malloc(sizeof(newnode));
    newnode->data = data;
    newnode->next = NULL;

    newnode->next = head;
    head = newnode;

Also I am confused why are you using this loop in insert function

 while( p-> next != NULL){
            p = p->next;
        }

I guess your code will work without it too.

Collapse
saral profile image
Saral Karki Author

Thank you so much for taking the time to go through the code and for the feedback.
I definitely see the point you make about the head, and it makes a lot of sense.

As for the while loop on the insert, there is no use for *P, and I don't know why I put it there.

Collapse
wiz profile image
wiz

Plus you can also try double pointers i.e passing a double pointer to head to the functions and abstain from returning head to update the actual head :)