I have implemented a LinkedList
with the ability to add, get elements from a particular position and ability to show all the elements in the array in to the console (main purpose to implement this was to ensure that all the elements are being populated in the LinkedList
correctly).
I would highly appreciate comments based on:
- The efficiency of my code
- Conceptual misinterpretations of a linked list, if any
- Violations of best practices
- Better way of achieving this
This is the code I have written:
#include <stdio.h>
#include <stdlib.h>
struct Element {
int value;
struct Element *nextElement;
};
struct LinkedList {
struct Element *firstElement;
};
void add(struct LinkedList *list, int value) {
if(list->firstElement == NULL) {
struct Element *newElement;
newElement = malloc(sizeof(struct Element));
newElement->value = value;
newElement->nextElement = NULL;
list->firstElement = newElement;
} else {
struct Element *lastElement;
lastElement = list->firstElement;
while(lastElement->nextElement != NULL) {
lastElement = lastElement->nextElement;
}
struct Element *newElement;
newElement = malloc(sizeof(struct Element));
newElement->value = value;
newElement->nextElement = NULL;
lastElement->nextElement = newElement;
}
}
int getElement(struct LinkedList *list, int index) {
int iteratedIndex = 0;
int returnValue = 0;
struct Element *temporaryElement = list->firstElement;
while(temporaryElement != NULL) {
if(iteratedIndex == index) {
returnValue = temporaryElement->value;
return returnValue;
}
iteratedIndex = iteratedIndex + 1;
temporaryElement = temporaryElement->nextElement;
}
return 0;
}
void showAllElements(struct LinkedList *list) {
struct Element *lastElement = list->firstElement;
while(lastElement != NULL) {
printf("%d\n", lastElement->value);
lastElement = lastElement->nextElement;
}
}
int main()
{
struct LinkedList list = {NULL};
add(&list, 5);
add(&list, 10);
add(&list, 15);
showAllElements(&list);
int value = getElement(&list, 0);
printf("%d\n", value);
return 0;
}
Here's the output I got:
5 10 15 5
Which is correct, first three listing all the elements in the LinkedList
and last one fetching the element in the 0th index.