Linked Lists
So I've been playing around with linked lists and was wondering why this doesn't work (the node was not added to the front of the list)
int main() {
node_t *linkedList = malloc(sizeof(node_t));
linkedList->value = 1;
linkedList->next = NULL;
addToEndOfLinkedList(linkedList, 10);
addToEndOfLinkedList(linkedList, 32);
addToFrontOfLinkedList(linkedList, 83);
printLinkedList(linkedList);
}
but when I changed it to this it did work (the node is added to the front and printed out).
int main() {
node_t *linkedList = malloc(sizeof(node_t));
linkedList->value = 1;
linkedList->next = NULL;
addToEndOfLinkedList(linkedList, 10);
addToEndOfLinkedList(linkedList, 32);
node_t *updatedList = addToFrontOfLinkedList(linkedList, 83);
printLinkedList(updatedList);
}
The 'addToEndOfLinkedList' returns a pointer to the second last node and the 'addToFrontOfLinkedList' returns a pointer to the head of the list. I didn't include all my code since it's saved on a different computer but will update if needed so you can see my functions. I'm also aware of memory leaks and have free'd the list in my code. This is just from the top of my head. The print function just iterates through the list and prints the value at each node.
one more question, do I have to typecast malloc?
my code
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int value;
struct Node *next;
} node_t;
void printLinkedList(node_t *head) {
int elementCounter = 1;
node_t *current = head;
while (current != NULL) {
printf("Value at Node %d is %d\n", elementCounter, current->value);
elementCounter++;
current = current->next;
}
}
node_t *addToFrontOfLinkedList(node_t *linkedListHead, int valueToSet) {
node_t *newHead = malloc(sizeof(node_t));
if (newHead == NULL) {
printf("Memory can't be allocated for the new node");
return NULL;
}
else {
newHead->value = valueToSet;
newHead->next = linkedListHead;
linkedListHead = newHead;
return linkedListHead;
}
}
node_t *addToEndOfLinkedList(node_t *linkedListHead, int valueToSet) {
node_t *NodeToBeAdded = malloc(sizeof(node_t));
if (NodeToBeAdded == NULL) {
printf("Unable to allocate memory to NodeToBeAdded");
return NULL;
}
else {
NodeToBeAdded->value = valueToSet;
NodeToBeAdded->next = NULL;
node_t *current = linkedListHead;
while (current->next != NULL) {
current = current->next;
}
current->next = NodeToBeAdded;
return current;
}
}
Posted Jul 18, 2020, 10:18 AM UTC · edited
Is this a library you're using? Your own creation? Something from a website? Can you provide the source for the linked list to maybe help us understand it's implementation?
i was following along with this - https://www.learn-c.org/en/Linked_lists
I'm just trying to revise linked lists. Sorry, updated with my code now.